From 471877a3b8ebfb4e622b146f332116b3c50ed41d Mon Sep 17 00:00:00 2001 From: stevejpurves Date: Tue, 21 Nov 2023 22:44:00 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20executab?= =?UTF-8?q?lebooks/thebe@1ce79f6a21fdb7d0e08fe46cf36080edbaaf8e50=20?= =?UTF-8?q?=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service-worker.js | 1 + thebe-lite.min.js | 2 +- thebe-lite.min.js.map | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 service-worker.js diff --git a/service-worker.js b/service-worker.js new file mode 100644 index 00000000..b536db8c --- /dev/null +++ b/service-worker.js @@ -0,0 +1 @@ +"use strict";const CACHE="precache",broadcast=new BroadcastChannel("/api/drive.v1");function onInstall(t){self.skipWaiting(),t.waitUntil(cacheAll())}function onActivate(t){t.waitUntil(self.clients.claim())}async function onFetch(t){const{request:a}=t,n=new URL(t.request.url);let e=null;shouldBroadcast(n)?e=broadcastOne(a):shouldDrop(a,n)||(e=maybeFromCache(t)),e&&t.respondWith(e)}async function maybeFromCache(t){const{request:a}=t;let n=await fromCache(a);return n?t.waitUntil(refetch(a)):(n=await fetch(a),t.waitUntil(updateCache(a,n.clone()))),n}async function fromCache(t){const a=await openCache(),n=await a.match(t);return n&&404!==n.status?n:null}async function refetch(t){const a=await fetch(t);return await updateCache(t,a),a}function shouldBroadcast(t){return t.origin===location.origin&&t.pathname.includes("/api/drive")}function shouldDrop(t,a){return"GET"!==t.method||null===a.origin.match(/^http/)||a.pathname.includes("/api/")}async function broadcastOne(t){const a=new Promise((t=>{broadcast.onmessage=a=>{t(new Response(JSON.stringify(a.data)))}})),n=await t.json();return n.receiver="broadcast.ts",broadcast.postMessage(n),await a}async function openCache(){return await caches.open(CACHE)}async function updateCache(t,a){return(await openCache()).put(t,a)}async function cacheAll(){const t=await openCache();return await t.addAll([])}self.addEventListener("install",onInstall),self.addEventListener("activate",onActivate),self.addEventListener("fetch",onFetch); \ No newline at end of file diff --git a/thebe-lite.min.js b/thebe-lite.min.js index 6ee2d49a..a6c9bd23 100644 --- a/thebe-lite.min.js +++ b/thebe-lite.min.js @@ -1,3 +1,3 @@ /*! For license information please see thebe-lite.min.js.LICENSE.txt */ -(()=>{var __webpack_modules__={2918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseManager=void 0;const i=n(544),s=n(2700);t.BaseManager=class{constructor(e){var t;this._isDisposed=!1,this._disposed=new i.Signal(this),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._disposed.emit(void 0),i.Signal.clearData(this))}}},1611:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BuildManager=void 0;const i=n(8920),s=n(2700);t.BuildManager=class{constructor(e={}){var t;this._url="",this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings();const{baseUrl:n,appUrl:r}=this.serverSettings;this._url=i.URLExt.join(n,r,"api/build")}get isAvailable(){return"true"===i.PageConfig.getOption("buildAvailable").toLowerCase()}get shouldCheck(){return"true"===i.PageConfig.getOption("buildCheck").toLowerCase()}getStatus(){const{_url:e,serverSettings:t}=this;return s.ServerConnection.makeRequest(e,{},t).then((e=>{if(200!==e.status)throw new s.ServerConnection.ResponseError(e);return e.json()})).then((e=>{if("string"!=typeof e.status)throw new Error("Invalid data");if("string"!=typeof e.message)throw new Error("Invalid data");return e}))}build(){const{_url:e,serverSettings:t}=this;return s.ServerConnection.makeRequest(e,{method:"POST"},t).then((e=>{if(400===e.status)throw new s.ServerConnection.ResponseError(e,"Build aborted");if(200!==e.status){const t=`Build failed with ${e.status}.\n\n If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').\n\n If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;throw new s.ServerConnection.ResponseError(e,t)}}))}cancel(){const{_url:e,serverSettings:t}=this;return s.ServerConnection.makeRequest(e,{method:"DELETE"},t).then((e=>{if(204!==e.status)throw new s.ServerConnection.ResponseError(e)}))}}},2677:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConfigWithDefaults=t.ConfigSection=void 0;const i=n(8920),s=n(6914);(t.ConfigSection||(t.ConfigSection={})).create=function(e){const t=new r(e);return t.load().then((()=>t))};class r{constructor(e){var t;this._url="unknown";const n=this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings();this._url=i.URLExt.join(n.baseUrl,"api/config",encodeURIComponent(e.name))}get data(){return this._data}async load(){const e=await s.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(200!==e.status)throw await s.ServerConnection.ResponseError.create(e);this._data=await e.json()}async update(e){this._data={...this._data,...e};const t={method:"PATCH",body:JSON.stringify(e)},n=await s.ServerConnection.makeRequest(this._url,t,this.serverSettings);if(200!==n.status)throw await s.ServerConnection.ResponseError.create(n);return this._data=await n.json(),this._data}}t.ConfigWithDefaults=class{constructor(e){var t,n;this._className="",this._section=e.section,this._defaults=null!==(t=e.defaults)&&void 0!==t?t:{},this._className=null!==(n=e.className)&&void 0!==n?n:""}get(e){const t=this._classData();return e in t?t[e]:this._defaults[e]}set(e,t){const n={};if(n[e]=t,this._className){const e={};return e[this._className]=n,this._section.update(e)}return this._section.update(n)}_classData(){const e=this._section.data;return this._className&&this._className in e?e[this._className]:e}}},7593:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Drive=t.ContentsManager=t.Contents=void 0;const o=n(8920),a=n(544),l=n(6914),c=r(n(7033));var u,d;(d=t.Contents||(t.Contents={})).validateContentsModel=function(e){c.validateContentsModel(e)},d.validateCheckpointModel=function(e){c.validateCheckpointModel(e)},t.ContentsManager=class{constructor(e={}){var t,n;this._isDisposed=!1,this._additionalDrives=new Map,this._fileChanged=new a.Signal(this);const i=this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:l.ServerConnection.makeSettings();this._defaultDrive=null!==(n=e.defaultDrive)&&void 0!==n?n:new h({serverSettings:i}),this._defaultDrive.fileChanged.connect(this._onFileChanged,this)}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,a.Signal.clearData(this))}addDrive(e){this._additionalDrives.set(e.name,e),e.fileChanged.connect(this._onFileChanged,this)}getSharedModelFactory(e){var t;const[n]=this._driveForPath(e);return null!==(t=null==n?void 0:n.sharedModelFactory)&&void 0!==t?t:null}localPath(e){const t=e.split("/"),n=t[0].split(":");return 1!==n.length&&this._additionalDrives.has(n[0])?o.PathExt.join(n.slice(1).join(":"),...t.slice(1)):o.PathExt.removeSlash(e)}normalize(e){const t=e.split(":");return 1===t.length?o.PathExt.normalize(e):`${t[0]}:${o.PathExt.normalize(t.slice(1).join(":"))}`}resolvePath(e,t){const n=this.driveName(e),i=this.localPath(e),s=o.PathExt.resolve("/",i,t);return n?`${n}:${s}`:s}driveName(e){const t=e.split("/")[0].split(":");return 1===t.length?"":this._additionalDrives.has(t[0])?t[0]:""}get(e,t){const[n,i]=this._driveForPath(e);return n.get(i,t).then((e=>{const t=[];if("directory"===e.type&&e.content){for(const i of e.content)t.push({...i,path:this._toGlobalPath(n,i.path)});return{...e,path:this._toGlobalPath(n,i),content:t,serverPath:e.path}}return{...e,path:this._toGlobalPath(n,i),serverPath:e.path}}))}getDownloadUrl(e){const[t,n]=this._driveForPath(e);return t.getDownloadUrl(n)}newUntitled(e={}){if(e.path){const t=this.normalize(e.path),[n,i]=this._driveForPath(t);return n.newUntitled({...e,path:i}).then((e=>({...e,path:o.PathExt.join(t,e.name),serverPath:e.path})))}return this._defaultDrive.newUntitled(e)}delete(e){const[t,n]=this._driveForPath(e);return t.delete(n)}rename(e,t){const[n,i]=this._driveForPath(e),[s,r]=this._driveForPath(t);if(n!==s)throw Error("ContentsManager: renaming files must occur within a Drive");return n.rename(i,r).then((e=>({...e,path:this._toGlobalPath(n,r),serverPath:e.path})))}save(e,t={}){const n=this.normalize(e),[i,s]=this._driveForPath(e);return i.save(s,{...t,path:s}).then((e=>({...e,path:n,serverPath:e.path})))}copy(e,t){const[n,i]=this._driveForPath(e),[s,r]=this._driveForPath(t);if(n===s)return n.copy(i,r).then((e=>({...e,path:this._toGlobalPath(n,e.path),serverPath:e.path})));throw Error("Copying files between drives is not currently implemented")}createCheckpoint(e){const[t,n]=this._driveForPath(e);return t.createCheckpoint(n)}listCheckpoints(e){const[t,n]=this._driveForPath(e);return t.listCheckpoints(n)}restoreCheckpoint(e,t){const[n,i]=this._driveForPath(e);return n.restoreCheckpoint(i,t)}deleteCheckpoint(e,t){const[n,i]=this._driveForPath(e);return n.deleteCheckpoint(i,t)}_toGlobalPath(e,t){return e===this._defaultDrive?o.PathExt.removeSlash(t):`${e.name}:${o.PathExt.removeSlash(t)}`}_driveForPath(e){const t=this.driveName(e),n=this.localPath(e);return t?[this._additionalDrives.get(t),n]:[this._defaultDrive,n]}_onFileChanged(e,t){var n,i;if(e===this._defaultDrive)this._fileChanged.emit(t);else{let s=null,r=null;(null===(n=t.newValue)||void 0===n?void 0:n.path)&&(s={...t.newValue,path:this._toGlobalPath(e,t.newValue.path)}),(null===(i=t.oldValue)||void 0===i?void 0:i.path)&&(r={...t.oldValue,path:this._toGlobalPath(e,t.oldValue.path)}),this._fileChanged.emit({type:t.type,newValue:s,oldValue:r})}}};class h{constructor(e={}){var t,n,i;this._isDisposed=!1,this._fileChanged=new a.Signal(this),this.name=null!==(t=e.name)&&void 0!==t?t:"Default",this._apiEndpoint=null!==(n=e.apiEndpoint)&&void 0!==n?n:"api/contents",this.serverSettings=null!==(i=e.serverSettings)&&void 0!==i?i:l.ServerConnection.makeSettings()}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,a.Signal.clearData(this))}async get(e,t){let n=this._getUrl(e);if(t){"notebook"===t.type&&delete t.format;const e=t.content?"1":"0",i={...t,content:e};n+=o.URLExt.objectToQueryString(i)}const i=this.serverSettings,s=await l.ServerConnection.makeRequest(n,{},i);if(200!==s.status)throw await l.ServerConnection.ResponseError.create(s);const r=await s.json();return c.validateContentsModel(r),r}getDownloadUrl(e){const t=this.serverSettings.baseUrl;let n=o.URLExt.join(t,"files",o.URLExt.encodeParts(e));const i=document.cookie.match("\\b_xsrf=([^;]*)\\b");if(i){const e=new URL(n);e.searchParams.append("_xsrf",i[1]),n=e.toString()}return Promise.resolve(n)}async newUntitled(e={}){var t;let n="{}";e&&(e.ext&&(e.ext=u.normalizeExtension(e.ext)),n=JSON.stringify(e));const i=this.serverSettings,s=this._getUrl(null!==(t=e.path)&&void 0!==t?t:""),r={method:"POST",body:n},o=await l.ServerConnection.makeRequest(s,r,i);if(201!==o.status)throw await l.ServerConnection.ResponseError.create(o);const a=await o.json();return c.validateContentsModel(a),this._fileChanged.emit({type:"new",oldValue:null,newValue:a}),a}async delete(e){const t=this._getUrl(e),n=this.serverSettings,i=await l.ServerConnection.makeRequest(t,{method:"DELETE"},n);if(204!==i.status)throw await l.ServerConnection.ResponseError.create(i);this._fileChanged.emit({type:"delete",oldValue:{path:e},newValue:null})}async rename(e,t){const n=this.serverSettings,i=this._getUrl(e),s={method:"PATCH",body:JSON.stringify({path:t})},r=await l.ServerConnection.makeRequest(i,s,n);if(200!==r.status)throw await l.ServerConnection.ResponseError.create(r);const o=await r.json();return c.validateContentsModel(o),this._fileChanged.emit({type:"rename",oldValue:{path:e},newValue:o}),o}async save(e,t={}){const n=this.serverSettings,i=this._getUrl(e),s={method:"PUT",body:JSON.stringify(t)},r=await l.ServerConnection.makeRequest(i,s,n);if(200!==r.status&&201!==r.status)throw await l.ServerConnection.ResponseError.create(r);const o=await r.json();return c.validateContentsModel(o),this._fileChanged.emit({type:"save",oldValue:null,newValue:o}),o}async copy(e,t){const n=this.serverSettings,i=this._getUrl(t),s={method:"POST",body:JSON.stringify({copy_from:e})},r=await l.ServerConnection.makeRequest(i,s,n);if(201!==r.status)throw await l.ServerConnection.ResponseError.create(r);const o=await r.json();return c.validateContentsModel(o),this._fileChanged.emit({type:"new",oldValue:null,newValue:o}),o}async createCheckpoint(e){const t=this._getUrl(e,"checkpoints"),n=await l.ServerConnection.makeRequest(t,{method:"POST"},this.serverSettings);if(201!==n.status)throw await l.ServerConnection.ResponseError.create(n);const i=await n.json();return c.validateCheckpointModel(i),i}async listCheckpoints(e){const t=this._getUrl(e,"checkpoints"),n=await l.ServerConnection.makeRequest(t,{},this.serverSettings);if(200!==n.status)throw await l.ServerConnection.ResponseError.create(n);const i=await n.json();if(!Array.isArray(i))throw new Error("Invalid Checkpoint list");for(let e=0;eo.URLExt.encodeParts(e))),n=this.serverSettings.baseUrl;return o.URLExt.join(n,this._apiEndpoint,...t)}}t.Drive=h,function(e){e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e}}(u||(u={}))},7033:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateCheckpointModel=t.validateContentsModel=void 0;const i=n(8193);t.validateContentsModel=function(e){(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"path","string"),(0,i.validateProperty)(e,"type","string"),(0,i.validateProperty)(e,"created","string"),(0,i.validateProperty)(e,"last_modified","string"),(0,i.validateProperty)(e,"mimetype","object"),(0,i.validateProperty)(e,"content","object"),(0,i.validateProperty)(e,"format","object")},t.validateCheckpointModel=function(e){(0,i.validateProperty)(e,"id","string"),(0,i.validateProperty)(e,"last_modified","string")}},3354:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventManager=void 0;const i=n(8920),s=n(9033),r=n(544),o=n(2700),a="api/events";t.EventManager=class{constructor(e={}){var t;this._socket=null,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:o.ServerConnection.makeSettings(),this._poll=new s.Poll({factory:()=>this._subscribe()}),this._stream=new r.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const e=this._socket;e&&(this._socket=null,e.onopen=()=>{},e.onerror=()=>{},e.onmessage=()=>{},e.onclose=()=>{},e.close()),r.Signal.clearData(this),this._stream.stop()}async emit(e){const{serverSettings:t}=this,{baseUrl:n,token:s}=t,{makeRequest:r,ResponseError:l}=o.ServerConnection,c=i.URLExt.join(n,a)+(s?`?token=${s}`:""),u={body:JSON.stringify(e),method:"POST"},d=await r(c,u,t);if(204!==d.status)throw new l(d)}_subscribe(){return new Promise(((e,t)=>{if(this.isDisposed)return;const{token:n,WebSocket:s,wsUrl:r}=this.serverSettings,o=i.URLExt.join(r,a,"subscribe")+(n?`?token=${encodeURIComponent(n)}`:""),l=this._socket=new s(o),c=this._stream;l.onclose=()=>t(new Error("EventManager socket closed")),l.onmessage=e=>e.data&&c.emit(JSON.parse(e.data))}))}}},6914:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(2918),t),s(n(2677),t),s(n(7593),t),s(n(3354),t),s(n(582),t),s(n(5312),t),s(n(8463),t),s(n(2700),t),s(n(7054),t),s(n(6052),t),s(n(8235),t),s(n(7523),t),s(n(87),t),s(n(4933),t)},5045:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CommHandler=void 0;const o=n(4643),a=r(n(1632));class l extends o.DisposableDelegate{constructor(e,t,n,i){super(i),this._target="",this._id="",this._id=t,this._target=e,this._kernel=n}get commId(){return this._id}get targetName(){return this._target}get onClose(){return this._onClose}set onClose(e){this._onClose=e}get onMsg(){return this._onMsg}set onMsg(e){this._onMsg=e}open(e,t,n=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const i=a.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,target_name:this._target,data:null!=e?e:{}},metadata:t,buffers:n});return this._kernel.sendShellMessage(i,!1,!0)}send(e,t,n=[],i=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const s=a.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:e},metadata:t,buffers:n});return this._kernel.sendShellMessage(s,!1,i)}close(e,t,n=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const i=a.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:null!=e?e:{}},metadata:t,buffers:n}),s=this._kernel.sendShellMessage(i,!1,!0),r=this._onClose;return r&&r(a.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:null!=e?e:{}},metadata:t,buffers:n})),this.dispose(),s}}t.CommHandler=l},2094:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelConnection=void 0;const o=n(8920),a=n(5168),l=n(544),c=n(6914),u=n(5045),d=r(n(1632)),h=n(9178),p=n(7411),f=r(n(5537)),m=n(5312),g=r(n(925)),v="_RESTARTING_";class _{constructor(e){var t,n,i,s;this._createSocket=(e=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const t=this.serverSettings,n=o.URLExt.join(t.wsUrl,g.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),i=n.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/,"$1");console.debug(`Starting WebSocket: ${i}`);let s=o.URLExt.join(n,"channels?session_id="+encodeURIComponent(this._clientId));const r=t.token;t.appendToken&&""!==r&&(s+=`&token=${encodeURIComponent(r)}`);const a=e?this._supportedProtocols:[];this._ws=new t.WebSocket(s,a),this._ws.binaryType="arraybuffer";let l=!1;const u=async e=>{var n,i;if(!this._isDisposed){this._reason="",this._model=void 0;try{const n=await g.getKernelModel(this._id,t);this._model=n,"dead"===(null==n?void 0:n.execution_state)?this._updateStatus("dead"):this._onWSClose(e)}catch(t){if(t instanceof c.ServerConnection.NetworkError||503===(null===(n=t.response)||void 0===n?void 0:n.status)||424===(null===(i=t.response)||void 0===i?void 0:i.status)){const t=1e3*y.getRandomIntInclusive(10,30);setTimeout(u,t,e)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},d=async e=>{l||(l=!0,await u(e))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=d,this._ws.onerror=d},this._onWSOpen=e=>{if(""!==this._ws.protocol&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=e=>{let t;try{t=(0,p.deserialize)(e.data,this._ws.protocol),f.validateMessage(t)}catch(e){throw e.message=`Kernel message validation error: ${e.message}`,e}this._kernelSession=t.header.session,this._msgChain=this._msgChain.then((()=>this._handleMessage(t))).catch((e=>{e.message.startsWith("Canceled future for ")&&console.error(e)})),this._anyMessage.emit({msg:t,direction:"recv"})},this._onWSClose=e=>{this.isDisposed||this._reconnect()},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(d.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new a.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new l.Signal(this),this._connectionStatusChanged=new l.Signal(this),this._disposed=new l.Signal(this),this._iopubMessage=new l.Signal(this),this._anyMessage=new l.Signal(this),this._pendingInput=new l.Signal(this),this._unhandledMessage=new l.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._name=e.model.name,this._id=e.model.id,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:c.ServerConnection.makeSettings(),this._clientId=null!==(n=e.clientId)&&void 0!==n?n:a.UUID.uuid4(),this._username=null!==(i=e.username)&&void 0!==i?i:"",this.handleComms=null===(s=e.handleComms)||void 0===s||s,this._createSocket()}get disposed(){return this._disposed}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise||(this._specPromise=m.KernelSpecAPI.getSpecs(this.serverSettings).then((e=>e.kernelspecs[this._name]))),this._specPromise}clone(e={}){return new _({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,...e})}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),l.Signal.clearData(this))}sendShellMessage(e,t=!1,n=!0){return this._sendKernelShellControl(h.KernelShellFutureHandler,e,t,n)}sendControlMessage(e,t=!1,n=!0){return this._sendKernelShellControl(h.KernelControlFutureHandler,e,t,n)}_sendKernelShellControl(e,t,n=!1,i=!0){this._sendMessage(t),this._anyMessage.emit({msg:t,direction:"send"});const s=new e((()=>{const e=t.header.msg_id;this._futures.delete(e);const n=this._msgIdToDisplayIds.get(e);n&&(n.forEach((t=>{const n=this._displayIdToParentIds.get(t);if(n){const i=n.indexOf(e);if(-1===i)return;1===n.length?this._displayIdToParentIds.delete(t):(n.splice(i,1),this._displayIdToParentIds.set(t,n))}})),this._msgIdToDisplayIds.delete(e))}),t,n,i,this);return this._futures.set(t.header.msg_id,s),s}_sendMessage(e,t=!0){if("dead"===this.status)throw new Error("Kernel is dead");if((""===this._kernelSession||this._kernelSession===v)&&d.isInfoRequestMsg(e)){if("connected"===this.connectionStatus)return void this._ws.send((0,p.serialize)(e,this._ws.protocol));throw new Error("Could not send message: status is not connected")}if(t&&this._pendingMessages.length>0)this._pendingMessages.push(e);else if("connected"===this.connectionStatus&&this._kernelSession!==v)this._ws.send((0,p.serialize)(e,this._ws.protocol));else{if(!t)throw new Error("Could not send message");this._pendingMessages.push(e)}}async interrupt(){if(this.hasPendingInput=!1,"dead"===this.status)throw new Error("Kernel is dead");return g.interruptKernel(this.id,this.serverSettings)}async restart(){if("dead"===this.status)throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._kernelSession=v,await g.restartKernel(this.id,this.serverSettings),await this.reconnect(),this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const e=new a.PromiseDelegate,t=(n,i)=>{"connected"===i?(e.resolve(),this.connectionStatusChanged.disconnect(t,this)):"disconnected"===i&&(e.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(t,this))};return this.connectionStatusChanged.connect(t,this),this._reconnectAttempt=0,this._reconnect(),e.promise}async shutdown(){"dead"!==this.status&&await g.shutdownKernel(this.id,this.serverSettings),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const e=d.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,content:{}});let t;try{t=await y.handleShellMessage(this,e)}catch(e){if(this.isDisposed)return;throw e}if(this._errorIfDisposed(),t)return void 0===t.content.status&&(t.content.status="ok"),"ok"!==t.content.status?(this._info.reject("Kernel info reply errored"),t):(this._info.resolve(t.content),this._kernelSession=t.header.session,t)}requestComplete(e){const t=d.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestInspect(e){const t=d.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestHistory(e){const t=d.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestExecute(e,t=!0,n){const i=d.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,content:{silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1,...e},metadata:n});return this.sendShellMessage(i,!0,t)}requestDebug(e,t=!0){const n=d.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:e});return this.sendControlMessage(n,!0,t)}requestIsComplete(e){const t=d.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestCommInfo(e){const t=d.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}sendInputReply(e,t){const n=d.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:e});n.parent_header=t,this._sendMessage(n),this._anyMessage.emit({msg:n,direction:"send"}),this.hasPendingInput=!1}createComm(e,t=a.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(t))throw new Error("Comm is already created");const n=new u.CommHandler(e,t,this,(()=>{this._unregisterComm(t)}));return this._comms.set(t,n),n}hasComm(e){return this._comms.has(e)}registerCommTarget(e,t){this.handleComms&&(this._targetRegistry[e]=t)}removeCommTarget(e,t){this.handleComms&&(this.isDisposed||this._targetRegistry[e]!==t||delete this._targetRegistry[e])}registerMessageHook(e,t){var n;const i=null===(n=this._futures)||void 0===n?void 0:n.get(e);i&&i.registerMessageHook(t)}removeMessageHook(e,t){var n;const i=null===(n=this._futures)||void 0===n?void 0:n.get(e);i&&i.removeMessageHook(t)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(e,t){var n,i;const s=t.parent_header.msg_id;let r=this._displayIdToParentIds.get(e);if(r){const e={header:a.JSONExt.deepCopy(t.header),parent_header:a.JSONExt.deepCopy(t.parent_header),metadata:a.JSONExt.deepCopy(t.metadata),content:a.JSONExt.deepCopy(t.content),channel:t.channel,buffers:t.buffers?t.buffers.slice():[]};e.header.msg_type="update_display_data",await Promise.all(r.map((async t=>{const n=this._futures&&this._futures.get(t);n&&await n.handleMsg(e)})))}if("update_display_data"===t.header.msg_type)return!0;r=null!==(n=this._displayIdToParentIds.get(e))&&void 0!==n?n:[],-1===r.indexOf(s)&&r.push(s),this._displayIdToParentIds.set(e,r);const o=null!==(i=this._msgIdToDisplayIds.get(s))&&void 0!==i?i:[];return-1===o.indexOf(s)&&o.push(s),this._msgIdToDisplayIds.set(s,o),!1}_clearSocket(){null!==this._ws&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(e){this._status!==e&&"dead"!==this._status&&(this._status=e,y.logKernelStatus(this),this._statusChanged.emit(e),"dead"===e&&this.dispose())}_sendPending(){for(;"connected"===this.connectionStatus&&this._kernelSession!==v&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach((e=>{e.dispose()})),this._comms.forEach((e=>{e.dispose()})),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(e){if(this._errorIfDisposed(),e.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${e.header.msg_type}`)}async _handleCommOpen(e){this._assertCurrentMessage(e);const t=e.content,n=new u.CommHandler(t.target_name,t.comm_id,this,(()=>{this._unregisterComm(t.comm_id)}));this._comms.set(t.comm_id,n);try{const i=await y.loadObject(t.target_name,t.target_module,this._targetRegistry);await i(n,e)}catch(e){throw n.close(),console.error("Exception opening new comm"),e}}async _handleCommClose(e){this._assertCurrentMessage(e);const t=e.content,n=this._comms.get(t.comm_id);if(!n)return void console.error("Comm not found for comm id "+t.comm_id);this._unregisterComm(n.commId);const i=n.onClose;i&&await i(e),n.dispose()}async _handleCommMsg(e){this._assertCurrentMessage(e);const t=e.content,n=this._comms.get(t.comm_id);if(!n)return;const i=n.onMsg;i&&await i(e)}_unregisterComm(e){this._comms.delete(e)}_updateConnectionStatus(e){if(this._connectionStatus!==e){if(this._connectionStatus=e,"connecting"!==e&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),"dead"!==this.status)if("connected"===e){let e=this._kernelSession===v,t=this.requestKernelInfo(),n=!1,i=()=>{n||(n=!0,e&&this._kernelSession===v&&(this._kernelSession=""),clearTimeout(s),this._pendingMessages.length>0&&this._sendPending())};t.then(i);let s=setTimeout(i,3e3)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(e)}}async _handleMessage(e){var t,n;let i=!1;if(e.parent_header&&"iopub"===e.channel&&(d.isDisplayDataMsg(e)||d.isUpdateDisplayDataMsg(e)||d.isExecuteResultMsg(e))){const n=(null!==(t=e.content.transient)&&void 0!==t?t:{}).display_id;n&&(i=await this._handleDisplayId(n,e),this._assertCurrentMessage(e))}if(!i&&e.parent_header){const t=e.parent_header,i=null===(n=this._futures)||void 0===n?void 0:n.get(t.msg_id);if(i)await i.handleMsg(e),this._assertCurrentMessage(e);else{const n=t.session===this.clientId;"iopub"!==e.channel&&n&&this._unhandledMessage.emit(e)}}if("iopub"===e.channel){switch(e.header.msg_type){case"status":{const t=e.content.execution_state;"restarting"===t&&Promise.resolve().then((async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()})),this._updateStatus(t);break}case"comm_open":this.handleComms&&await this._handleCommOpen(e);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(e);break;case"comm_close":this.handleComms&&await this._handleCommClose(e)}this.isDisposed||(this._assertCurrentMessage(e),this._iopubMessage.emit(e))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt{if(t){if("undefined"==typeof requirejs)throw new Error("requirejs not found");requirejs([t],(n=>{void 0===n[e]?s(new Error(`Object '${e}' not found in module '${t}'`)):i(n[e])}),s)}else(null==n?void 0:n[e])?i(n[e]):s(new Error(`Object '${e}' not found in registry`))}))},e.getRandomIntInclusive=function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}}(y||(y={}))},9178:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelShellFutureHandler=t.KernelControlFutureHandler=t.KernelFutureHandler=void 0;const o=n(5168),a=n(4643),l=r(n(1632));class c extends a.DisposableDelegate{constructor(e,t,n,i,s){super(e),this._status=0,this._stdin=u.noOp,this._iopub=u.noOp,this._reply=u.noOp,this._done=new o.PromiseDelegate,this._hooks=new u.HookList,this._disposeOnDone=!0,this._msg=t,n||this._setFlag(u.KernelFutureFlag.GotReply),this._disposeOnDone=i,this._kernel=s}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(e){this._reply=e}get onIOPub(){return this._iopub}set onIOPub(e){this._iopub=e}get onStdin(){return this._stdin}set onStdin(e){this._stdin=e}registerMessageHook(e){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(e)}removeMessageHook(e){this.isDisposed||this._hooks.remove(e)}sendInputReply(e,t){this._kernel.sendInputReply(e,t)}dispose(){this._stdin=u.noOp,this._iopub=u.noOp,this._reply=u.noOp,this._hooks=null,this._testFlag(u.KernelFutureFlag.IsDone)||(this._done.promise.catch((()=>{})),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(e){switch(e.channel){case"control":case"shell":e.channel===this.msg.channel&&e.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(e);break;case"stdin":await this._handleStdin(e);break;case"iopub":await this._handleIOPub(e)}}async _handleReply(e){const t=this._reply;t&&await t(e),this._replyMsg=e,this._setFlag(u.KernelFutureFlag.GotReply),this._testFlag(u.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(e){this._kernel.hasPendingInput=!0;const t=this._stdin;t&&await t(e)}async _handleIOPub(e){const t=await this._hooks.process(e),n=this._iopub;t&&n&&await n(e),l.isStatusMsg(e)&&"idle"===e.content.execution_state&&(this._setFlag(u.KernelFutureFlag.GotIdle),this._testFlag(u.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(u.KernelFutureFlag.IsDone)||(this._setFlag(u.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(e){return 0!=(this._status&e)}_setFlag(e){this._status|=e}}var u;t.KernelFutureHandler=c,t.KernelControlFutureHandler=class extends c{},t.KernelShellFutureHandler=class extends c{},function(e){e.noOp=()=>{};const t="function"==typeof requestAnimationFrame?requestAnimationFrame:setImmediate;let n;e.HookList=class{constructor(){this._hooks=[]}add(e){this.remove(e),this._hooks.push(e)}remove(e){const t=this._hooks.indexOf(e);t>=0&&(this._hooks[t]=null,this._scheduleCompact())}async process(e){await this._processing;const t=new o.PromiseDelegate;let n;this._processing=t.promise;for(let i=this._hooks.length-1;i>=0;i--){const s=this._hooks[i];if(null!==s){try{n=await s(e)}catch(e){n=!0,console.error(e)}if(!1===n)return t.resolve(void 0),!1}}return t.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,t((()=>{this._processing=this._processing.then((()=>{this._compactScheduled=!1,this._compact()}))})))}_compact(){let e=0;for(let t=0,n=this._hooks.length;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},2810:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KernelManager=void 0;const i=n(9033),s=n(544),r=n(6914),o=n(2918),a=n(925),l=n(2094);class c extends o.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new s.Signal(this),this._connectionFailure=new s.Signal(this),this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:KernelManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}connectTo(e){var t;const{id:n}=e.model;let i=null===(t=e.handleComms)||void 0===t||t;if(void 0===e.handleComms)for(const e of this._kernelConnections)if(e.id===n&&e.handleComms){i=!1;break}const s=new l.KernelConnection({handleComms:i,...e,serverSettings:this.serverSettings});return this._onStarted(s),this._models.has(n)||this.refreshRunning().catch((()=>{})),s}running(){return this._models.values()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e={},t={}){const n=await(0,a.startNew)(e,this.serverSettings);return this.connectTo({...t,model:n})}async shutdown(e){await(0,a.shutdownKernel)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map((e=>(0,a.shutdownKernel)(e,this.serverSettings)))),await this.refreshRunning()}async findById(e){return this._models.has(e)||await this.refreshRunning(),this._models.get(e)}async requestRunning(){var e,t;let n;try{n=await(0,a.listRunning)(this.serverSettings)}catch(n){throw(n instanceof r.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}this.isDisposed||this._models.size===n.length&&n.every((e=>{const t=this._models.get(e.id);return!!t&&t.connections===e.connections&&t.execution_state===e.execution_state&&t.last_activity===e.last_activity&&t.name===e.name&&t.reason===e.reason&&t.traceback===e.traceback}))||(this._models=new Map(n.map((e=>[e.id,e]))),this._kernelConnections.forEach((e=>{this._models.has(e.id)||e.handleShutdown()})),this._runningChanged.emit(n))}_onStarted(e){this._kernelConnections.add(e),e.statusChanged.connect(this._onStatusChanged,this),e.disposed.connect(this._onDisposed,this)}_onDisposed(e){this._kernelConnections.delete(e),this.refreshRunning().catch((()=>{}))}_onStatusChanged(e,t){"dead"===t&&this.refreshRunning().catch((()=>{}))}}t.KernelManager=c,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}async startNew(e={},t={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(e){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then((()=>this._readyPromise))}async requestRunning(){return Promise.resolve()}}}(c=t.KernelManager||(t.KernelManager={}))},1632:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.supportedKernelWebSocketProtocols=t.isInputReplyMsg=t.isInputRequestMsg=t.isDebugReplyMsg=t.isDebugRequestMsg=t.isExecuteReplyMsg=t.isInfoRequestMsg=t.isCommMsgMsg=t.isCommCloseMsg=t.isCommOpenMsg=t.isDebugEventMsg=t.isClearOutputMsg=t.isStatusMsg=t.isErrorMsg=t.isExecuteResultMsg=t.isExecuteInputMsg=t.isUpdateDisplayDataMsg=t.isDisplayDataMsg=t.isStreamMsg=t.createMessage=void 0;const i=n(5168);t.createMessage=function(e){var t,n,s,r,o;return{buffers:null!==(t=e.buffers)&&void 0!==t?t:[],channel:e.channel,content:e.content,header:{date:(new Date).toISOString(),msg_id:null!==(n=e.msgId)&&void 0!==n?n:i.UUID.uuid4(),msg_type:e.msgType,session:e.session,username:null!==(s=e.username)&&void 0!==s?s:"",version:"5.2"},metadata:null!==(r=e.metadata)&&void 0!==r?r:{},parent_header:null!==(o=e.parentHeader)&&void 0!==o?o:{}}},t.isStreamMsg=function(e){return"stream"===e.header.msg_type},t.isDisplayDataMsg=function(e){return"display_data"===e.header.msg_type},t.isUpdateDisplayDataMsg=function(e){return"update_display_data"===e.header.msg_type},t.isExecuteInputMsg=function(e){return"execute_input"===e.header.msg_type},t.isExecuteResultMsg=function(e){return"execute_result"===e.header.msg_type},t.isErrorMsg=function(e){return"error"===e.header.msg_type},t.isStatusMsg=function(e){return"status"===e.header.msg_type},t.isClearOutputMsg=function(e){return"clear_output"===e.header.msg_type},t.isDebugEventMsg=function(e){return"debug_event"===e.header.msg_type},t.isCommOpenMsg=function(e){return"comm_open"===e.header.msg_type},t.isCommCloseMsg=function(e){return"comm_close"===e.header.msg_type},t.isCommMsgMsg=function(e){return"comm_msg"===e.header.msg_type},t.isInfoRequestMsg=function(e){return"kernel_info_request"===e.header.msg_type},t.isExecuteReplyMsg=function(e){return"execute_reply"===e.header.msg_type},t.isDebugRequestMsg=function(e){return"debug_request"===e.header.msg_type},t.isDebugReplyMsg=function(e){return"debug_reply"===e.header.msg_type},t.isInputRequestMsg=function(e){return"input_request"===e.header.msg_type},t.isInputReplyMsg=function(e){return"input_reply"===e.header.msg_type},(t.supportedKernelWebSocketProtocols||(t.supportedKernelWebSocketProtocols={})).v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"},925:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getKernelModel=t.shutdownKernel=t.interruptKernel=t.restartKernel=t.startNew=t.listRunning=t.KERNEL_SERVICE_URL=void 0;const i=n(2700),s=n(8920),r=n(5537);t.KERNEL_SERVICE_URL="api/kernels",t.listRunning=async function(e=i.ServerConnection.makeSettings()){const n=s.URLExt.join(e.baseUrl,t.KERNEL_SERVICE_URL),o=await i.ServerConnection.makeRequest(n,{},e);if(200!==o.status)throw await i.ServerConnection.ResponseError.create(o);const a=await o.json();return(0,r.validateModels)(a),a},t.startNew=async function(e={},n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL),a={method:"POST",body:JSON.stringify(e)},l=await i.ServerConnection.makeRequest(o,a,n);if(201!==l.status)throw await i.ServerConnection.ResponseError.create(l);const c=await l.json();return(0,r.validateModel)(c),c},t.restartKernel=async function(e,n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e),"restart"),a=await i.ServerConnection.makeRequest(o,{method:"POST"},n);if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();(0,r.validateModel)(l)},t.interruptKernel=async function(e,n=i.ServerConnection.makeSettings()){const r=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e),"interrupt"),o=await i.ServerConnection.makeRequest(r,{method:"POST"},n);if(204!==o.status)throw await i.ServerConnection.ResponseError.create(o)},t.shutdownKernel=async function(e,n=i.ServerConnection.makeSettings()){const r=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e)),o=await i.ServerConnection.makeRequest(r,{method:"DELETE"},n);if(404===o.status){const t=`The kernel "${e}" does not exist on the server`;console.warn(t)}else if(204!==o.status)throw await i.ServerConnection.ResponseError.create(o)},t.getKernelModel=async function(e,n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e)),a=await i.ServerConnection.makeRequest(o,{},n);if(404===a.status)return;if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();return(0,r.validateModel)(l),l}},7411:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.deserialize=t.serialize=void 0;const o=r(n(1632));var a;t.serialize=function(e,t=""){return t===o.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?a.serializeV1KernelWebsocketJupyterOrg(e):a.serializeDefault(e)},t.deserialize=function(e,t=""){return t===o.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?a.deserializeV1KernelWebsocketJupyterOrg(e):a.deserializeDefault(e)},function(e){e.deserializeV1KernelWebsocketJupyterOrg=function(e){let t;const n=new DataView(e),i=Number(n.getBigUint64(0,!0));let s=[];for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateModels=t.validateModel=t.validateMessage=void 0;const i=n(8193),s=["username","version","session","msg_id","msg_type"],r={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function o(e){(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"id","string")}t.validateMessage=function(e){(0,i.validateProperty)(e,"metadata","object"),(0,i.validateProperty)(e,"content","object"),(0,i.validateProperty)(e,"channel","string"),function(e){for(let t=0;to(e)))}},5312:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t},o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSpecAPI=t.KernelSpec=void 0;const a=r(n(523));t.KernelSpec=a;const l=r(n(7352));t.KernelSpecAPI=l,o(n(3973),t)},523:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},3973:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSpecManager=void 0;const o=n(5168),a=n(9033),l=n(544),c=r(n(7352)),u=n(2918);class d extends u.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._connectionFailure=new l.Signal(this),this._specs=null,this._specsChanged=new l.Signal(this),this._ready=Promise.all([this.requestSpecs()]).then((e=>{})).catch((e=>{})).then((()=>{this.isDisposed||(this._isReady=!0)})),this._pollSpecs=new a.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61e3,backoff:!0,max:3e5},name:"@jupyterlab/services:KernelSpecManager#specs",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this.ready.then((()=>{this._pollSpecs.start()}))}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const e=await c.getSpecs(this.serverSettings);this.isDisposed||o.JSONExt.deepEqual(e,this._specs)||(this._specs=e,this._specsChanged.emit(e))}}t.KernelSpecManager=d},7352:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSpecs=void 0;const i=n(2700),s=n(7),r=n(8920);t.getSpecs=async function(e=i.ServerConnection.makeSettings()){const t=r.URLExt.join(e.baseUrl,"api/kernelspecs"),n=await i.ServerConnection.makeRequest(t,{},e);if(200!==n.status)throw await i.ServerConnection.ResponseError.create(n);const o=await n.json();return(0,s.validateSpecModels)(o)}},7:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSpecModels=t.validateSpecModel=void 0;const i=n(8193);function s(e){const t=e.spec;if(!t)throw new Error("Invalid kernel spec");(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"resources","object"),(0,i.validateProperty)(t,"language","string"),(0,i.validateProperty)(t,"display_name","string"),(0,i.validateProperty)(t,"argv","array");let n=null;t.hasOwnProperty("metadata")&&((0,i.validateProperty)(t,"metadata","object"),n=t.metadata);let s=null;return t.hasOwnProperty("env")&&((0,i.validateProperty)(t,"env","object"),s=t.env),{name:e.name,resources:e.resources,language:t.language,display_name:t.display_name,argv:t.argv,metadata:n,env:s}}t.validateSpecModel=s,t.validateSpecModels=function(e){if(!e.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let t=Object.keys(e.kernelspecs);const n=Object.create(null);let i=e.default;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceManager=void 0;const i=n(544),s=n(1611),r=n(7593),o=n(3354),a=n(582),l=n(5312),c=n(4933),u=n(2700),d=n(7054),h=n(6052),p=n(8235),f=n(7523),m=n(87);t.ServiceManager=class{constructor(e={}){var t,n;this._isDisposed=!1,this._connectionFailure=new i.Signal(this),this._isReady=!1;const g=e.defaultDrive,v=null!==(t=e.serverSettings)&&void 0!==t?t:u.ServerConnection.makeSettings(),_={defaultDrive:g,serverSettings:v,standby:null!==(n=e.standby)&&void 0!==n?n:"when-hidden"};this.serverSettings=v,this.contents=e.contents||new r.ContentsManager(_),this.events=e.events||new o.EventManager(_),this.kernels=e.kernels||new a.KernelManager(_),this.sessions=e.sessions||new d.SessionManager({..._,kernelManager:this.kernels}),this.settings=e.settings||new h.SettingManager(_),this.terminals=e.terminals||new p.TerminalManager(_),this.builder=e.builder||new s.BuildManager(_),this.workspaces=e.workspaces||new m.WorkspaceManager(_),this.nbconvert=e.nbconvert||new c.NbConvertManager(_),this.kernelspecs=e.kernelspecs||new l.KernelSpecManager(_),this.user=e.user||new f.UserManager(_),this.kernelspecs.connectionFailure.connect(this._onConnectionFailure,this),this.sessions.connectionFailure.connect(this._onConnectionFailure,this),this.terminals.connectionFailure.connect(this._onConnectionFailure,this);const y=[this.sessions.ready,this.kernelspecs.ready];this.terminals.isAvailable()&&y.push(this.terminals.ready),this._readyPromise=Promise.all(y).then((()=>{this._isReady=!0}))}get connectionFailure(){return this._connectionFailure}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,i.Signal.clearData(this),this.contents.dispose(),this.events.dispose(),this.sessions.dispose(),this.terminals.dispose())}get isReady(){return this._isReady}get ready(){return this._readyPromise}_onConnectionFailure(e,t){this._connectionFailure.emit(t)}}},4933:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NbConvertManager=void 0;const i=n(8920),s=n(2700),r=n(5168);t.NbConvertManager=class{constructor(e={}){var t;this._exportFormats=null,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings()}async fetchExportFormats(){this._requestingFormats=new r.PromiseDelegate,this._exportFormats=null;const e=this.serverSettings.baseUrl,t=i.URLExt.join(e,"api/nbconvert"),{serverSettings:n}=this,o=await s.ServerConnection.makeRequest(t,{},n);if(200!==o.status)throw await s.ServerConnection.ResponseError.create(o);const a=await o.json(),l={};return Object.keys(a).forEach((function(e){const t=a[e].output_mimetype;l[e]={output_mimetype:t}})),this._exportFormats=l,this._requestingFormats.resolve(l),l}async getExportFormats(e=!0){return this._requestingFormats?this._requestingFormats.promise:e||!this._exportFormats?await this.fetchExportFormats():this._exportFormats}}},2700:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServerConnection=void 0;const i=n(8920);let s;var r,o;s="undefined"==typeof window?n(2195):WebSocket,function(e){e.makeSettings=function(e){return o.makeSettings(e)},e.makeRequest=function(e,t,n){return o.handleRequest(e,t,n)};class t extends Error{static async create(e){try{const n=await e.json(),{message:i,traceback:s}=n;return s&&console.error(s),new t(e,null!=i?i:t._defaultMessage(e),null!=s?s:"")}catch(n){return console.debug(n),new t(e)}}constructor(e,n=t._defaultMessage(e),i=""){super(n),this.response=e,this.traceback=i}static _defaultMessage(e){return`Invalid response: ${e.status} ${e.statusText}`}}e.ResponseError=t;class n extends TypeError{constructor(e){super(e.message),this.stack=e.stack}}e.NetworkError=n}(r=t.ServerConnection||(t.ServerConnection={})),function(e){e.makeSettings=function(e={}){var t;const n=i.PageConfig.getBaseUrl(),r=i.PageConfig.getWsUrl(),o=i.URLExt.normalize(e.baseUrl)||n;let a=e.wsUrl;return a||o!==n||(a=r),a||0!==o.indexOf("http")||(a="ws"+o.slice(4)),a=null!=a?a:r,{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:s,token:i.PageConfig.getToken(),appUrl:i.PageConfig.getOption("appUrl"),appendToken:"undefined"==typeof window||"undefined"!=typeof process&&void 0!==(null===(t=null===process||void 0===process?void 0:{})||void 0===t?void 0:t.JEST_WORKER_ID)||i.URLExt.getHostName(n)!==i.URLExt.getHostName(a),...e,baseUrl:o,wsUrl:a}},e.handleRequest=function(e,t,n){var i;if(0!==e.indexOf(n.baseUrl))throw new Error("Can only be used for notebook server requests");"no-store"===(null!==(i=t.cache)&&void 0!==i?i:n.init.cache)&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());const s=new n.Request(e,{...n.init,...t});let o=!1;if(n.token&&(o=!0,s.headers.append("Authorization",`token ${n.token}`)),"undefined"!=typeof document&&(null===document||void 0===document?void 0:document.cookie)){const e=function(e){const t=document.cookie.match("\\b_xsrf=([^;]*)\\b");return null==t?void 0:t[1]}();void 0!==e&&(o=!0,s.headers.append("X-XSRFToken",e))}return!s.headers.has("Content-Type")&&o&&s.headers.set("Content-Type","application/json"),n.fetch.call(null,s).catch((e=>{throw new r.NetworkError(e)}))}}(o||(o={}))},5575:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionConnection=void 0;const i=n(544),s=n(6914),r=n(8351),o=n(5168);t.SessionConnection=class{constructor(e){var t,n,r,a;this._id="",this._path="",this._name="",this._type="",this._kernel=null,this._isDisposed=!1,this._disposed=new i.Signal(this),this._kernelChanged=new i.Signal(this),this._statusChanged=new i.Signal(this),this._connectionStatusChanged=new i.Signal(this),this._pendingInput=new i.Signal(this),this._iopubMessage=new i.Signal(this),this._unhandledMessage=new i.Signal(this),this._anyMessage=new i.Signal(this),this._propertyChanged=new i.Signal(this),this._id=e.model.id,this._name=e.model.name,this._path=e.model.path,this._type=e.model.type,this._username=null!==(t=e.username)&&void 0!==t?t:"",this._clientId=null!==(n=e.clientId)&&void 0!==n?n:o.UUID.uuid4(),this._connectToKernel=e.connectToKernel,this._kernelConnectionOptions=null!==(r=e.kernelConnectionOptions)&&void 0!==r?r:{},this.serverSettings=null!==(a=e.serverSettings)&&void 0!==a?a:s.ServerConnection.makeSettings(),this.setupKernel(e.model.kernel)}get disposed(){return this._disposed}get kernelChanged(){return this._kernelChanged}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get pendingInput(){return this._pendingInput}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get anyMessage(){return this._anyMessage}get propertyChanged(){return this._propertyChanged}get id(){return this._id}get kernel(){return this._kernel}get path(){return this._path}get type(){return this._type}get name(){return this._name}get model(){return{id:this.id,kernel:this.kernel&&{id:this.kernel.id,name:this.kernel.name},path:this._path,type:this._type,name:this._name}}get isDisposed(){return this._isDisposed}update(e){const t=this.model;if(this._path=e.path,this._name=e.name,this._type=e.type,null===this._kernel&&null!==e.kernel||null!==this._kernel&&null===e.kernel||null!==this._kernel&&null!==e.kernel&&this._kernel.id!==e.kernel.id){null!==this._kernel&&this._kernel.dispose();const t=this._kernel||null;this.setupKernel(e.kernel);const n=this._kernel||null;this._kernelChanged.emit({name:"kernel",oldValue:t,newValue:n})}this._handleModelChange(t)}dispose(){if(!this.isDisposed){if(this._isDisposed=!0,this._disposed.emit(),this._kernel){this._kernel.dispose();const e=this._kernel;this._kernel=null;const t=this._kernel;this._kernelChanged.emit({name:"kernel",oldValue:e,newValue:t})}i.Signal.clearData(this)}}async setPath(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({path:e})}async setName(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({name:e})}async setType(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({type:e})}async changeKernel(e){if(this.isDisposed)throw new Error("Session is disposed");return await this._patch({kernel:e}),this.kernel}async shutdown(){if(this.isDisposed)throw new Error("Session is disposed");await(0,r.shutdownSession)(this.id,this.serverSettings),this.dispose()}setupKernel(e){if(null===e)return void(this._kernel=null);const t=this._connectToKernel({...this._kernelConnectionOptions,model:e,username:this._username,clientId:this._clientId,serverSettings:this.serverSettings});this._kernel=t,t.statusChanged.connect(this.onKernelStatus,this),t.connectionStatusChanged.connect(this.onKernelConnectionStatus,this),t.pendingInput.connect(this.onPendingInput,this),t.unhandledMessage.connect(this.onUnhandledMessage,this),t.iopubMessage.connect(this.onIOPubMessage,this),t.anyMessage.connect(this.onAnyMessage,this)}onKernelStatus(e,t){this._statusChanged.emit(t)}onKernelConnectionStatus(e,t){this._connectionStatusChanged.emit(t)}onPendingInput(e,t){this._pendingInput.emit(t)}onIOPubMessage(e,t){this._iopubMessage.emit(t)}onUnhandledMessage(e,t){this._unhandledMessage.emit(t)}onAnyMessage(e,t){this._anyMessage.emit(t)}async _patch(e){const t=await(0,r.updateSession)({...e,id:this._id},this.serverSettings);return this.update(t),t}_handleModelChange(e){e.name!==this._name&&this._propertyChanged.emit("name"),e.type!==this._type&&this._propertyChanged.emit("type"),e.path!==this._path&&this._propertyChanged.emit("path")}}},7054:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t},o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SessionAPI=t.Session=void 0;const a=r(n(658));t.Session=a;const l=r(n(8351));t.SessionAPI=l,o(n(6699),t)},6699:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionManager=void 0;const i=n(9033),s=n(544),r=n(2700),o=n(2918),a=n(5575),l=n(8351);class c extends o.BaseManager{constructor(e){var t;super(e),this._isReady=!1,this._sessionConnections=new Set,this._models=new Map,this._runningChanged=new s.Signal(this),this._connectionFailure=new s.Signal(this),this._connectToKernel=e=>this._kernelManager.connectTo(e),this._kernelManager=e.kernelManager,this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:SessionManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._kernelManager.isActive&&await this._kernelManager.ready,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._models.clear(),this._sessionConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}connectTo(e){const t=new a.SessionConnection({...e,connectToKernel:this._connectToKernel,serverSettings:this.serverSettings});return this._onStarted(t),this._models.has(e.model.id)||this.refreshRunning().catch((()=>{})),t}running(){return this._models.values()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e,t={}){const n=await(0,l.startSession)(e,this.serverSettings);return await this.refreshRunning(),this.connectTo({...t,model:n})}async shutdown(e){await(0,l.shutdownSession)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map((e=>(0,l.shutdownSession)(e,this.serverSettings)))),await this.refreshRunning()}async stopIfNeeded(e){try{const t=(await(0,l.listRunning)(this.serverSettings)).filter((t=>t.path===e));if(1===t.length){const e=t[0].id;await this.shutdown(e)}}catch(e){}}async findById(e){return this._models.has(e)||await this.refreshRunning(),this._models.get(e)}async findByPath(e){for(const t of this._models.values())if(t.path===e)return t;await this.refreshRunning();for(const t of this._models.values())if(t.path===e)return t}async requestRunning(){var e,t;let n;try{n=await(0,l.listRunning)(this.serverSettings)}catch(n){throw(n instanceof r.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}this.isDisposed||this._models.size===n.length&&n.every((e=>{var t,n,i,s;const r=this._models.get(e.id);return!!r&&(null===(t=r.kernel)||void 0===t?void 0:t.id)===(null===(n=e.kernel)||void 0===n?void 0:n.id)&&(null===(i=r.kernel)||void 0===i?void 0:i.name)===(null===(s=e.kernel)||void 0===s?void 0:s.name)&&r.name===e.name&&r.path===e.path&&r.type===e.type}))||(this._models=new Map(n.map((e=>[e.id,e]))),this._sessionConnections.forEach((e=>{this._models.has(e.id)?e.update(this._models.get(e.id)):e.dispose()})),this._runningChanged.emit(n))}_onStarted(e){this._sessionConnections.add(e),e.disposed.connect(this._onDisposed,this),e.propertyChanged.connect(this._onChanged,this),e.kernelChanged.connect(this._onChanged,this)}_onDisposed(e){this._sessionConnections.delete(e),this.refreshRunning().catch((()=>{}))}_onChanged(){this.refreshRunning().catch((()=>{}))}}t.SessionManager=c,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}async startNew(e,t={}){return Promise.reject(new Error("Not implemented in no-op Session Manager"))}connectTo(e){throw Error("Not implemented in no-op Session Manager")}get ready(){return this.parentReady.then((()=>this._readyPromise))}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Session Manager"))}async requestRunning(){return Promise.resolve()}}}(c=t.SessionManager||(t.SessionManager={}))},8351:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateSession=t.startSession=t.getSessionModel=t.shutdownSession=t.getSessionUrl=t.listRunning=t.SESSION_SERVICE_URL=void 0;const i=n(2700),s=n(8920),r=n(8775);function o(e,n){return s.URLExt.join(e,t.SESSION_SERVICE_URL,n)}t.SESSION_SERVICE_URL="api/sessions",t.listRunning=async function(e=i.ServerConnection.makeSettings()){const n=s.URLExt.join(e.baseUrl,t.SESSION_SERVICE_URL),o=await i.ServerConnection.makeRequest(n,{},e);if(200!==o.status)throw await i.ServerConnection.ResponseError.create(o);const a=await o.json();if(!Array.isArray(a))throw new Error("Invalid Session list");return a.forEach((e=>{(0,r.updateLegacySessionModel)(e),(0,r.validateModel)(e)})),a},t.getSessionUrl=o,t.shutdownSession=async function(e,t=i.ServerConnection.makeSettings()){var n;const s=o(t.baseUrl,e),r=await i.ServerConnection.makeRequest(s,{method:"DELETE"},t);if(404===r.status){const t=null!==(n=(await r.json()).message)&&void 0!==n?n:`The session "${e}"" does not exist on the server`;console.warn(t)}else{if(410===r.status)throw new i.ServerConnection.ResponseError(r,"The kernel was deleted but the session was not");if(204!==r.status)throw await i.ServerConnection.ResponseError.create(r)}},t.getSessionModel=async function(e,t=i.ServerConnection.makeSettings()){const n=o(t.baseUrl,e),s=await i.ServerConnection.makeRequest(n,{},t);if(200!==s.status)throw await i.ServerConnection.ResponseError.create(s);const a=await s.json();return(0,r.updateLegacySessionModel)(a),(0,r.validateModel)(a),a},t.startSession=async function(e,n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.SESSION_SERVICE_URL),a={method:"POST",body:JSON.stringify(e)},l=await i.ServerConnection.makeRequest(o,a,n);if(201!==l.status)throw await i.ServerConnection.ResponseError.create(l);const c=await l.json();return(0,r.updateLegacySessionModel)(c),(0,r.validateModel)(c),c},t.updateSession=async function(e,t=i.ServerConnection.makeSettings()){const n=o(t.baseUrl,e.id),s={method:"PATCH",body:JSON.stringify(e)},a=await i.ServerConnection.makeRequest(n,s,t);if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();return(0,r.updateLegacySessionModel)(l),(0,r.validateModel)(l),l}},658:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},8775:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateModels=t.updateLegacySessionModel=t.validateModel=void 0;const i=n(5537),s=n(8193);function r(e){(0,s.validateProperty)(e,"id","string"),(0,s.validateProperty)(e,"type","string"),(0,s.validateProperty)(e,"name","string"),(0,s.validateProperty)(e,"path","string"),(0,s.validateProperty)(e,"kernel","object"),(0,i.validateModel)(e.kernel)}t.validateModel=r,t.updateLegacySessionModel=function(e){void 0===e.path&&void 0!==e.notebook&&(e.path=e.notebook.path,e.type="notebook",e.name="")},t.validateModels=function(e){if(!Array.isArray(e))throw new Error("Invalid session list");e.forEach((e=>r(e)))}},6052:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingManager=void 0;const i=n(8920),s=n(4116),r=n(2700);class o extends s.DataConnector{constructor(e={}){var t;super(),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings()}async fetch(e){if(!e)throw new Error("Plugin `id` parameter is required for settings fetch.");const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:s,ResponseError:o}=r.ServerConnection,l=n+i,c=a.url(l,e),u=await s(c,{},t);if(200!==u.status)throw await o.create(u);return u.json()}async list(e){var t,n,i,s;const{serverSettings:o}=this,{baseUrl:l,appUrl:c}=o,{makeRequest:u,ResponseError:d}=r.ServerConnection,h=l+c,p=a.url(h,"","ids"===e),f=await u(p,{},o);if(200!==f.status)throw new d(f);const m=await f.json(),g=null!==(n=null===(t=null==m?void 0:m.settings)||void 0===t?void 0:t.map((e=>e.id)))&&void 0!==n?n:[];let v=[];return e||(v=null!==(s=null===(i=null==m?void 0:m.settings)||void 0===i?void 0:i.map((e=>(e.data={composite:{},user:{}},e))))&&void 0!==s?s:[]),{ids:g,values:v}}async save(e,t){const{serverSettings:n}=this,{baseUrl:i,appUrl:s}=n,{makeRequest:o,ResponseError:l}=r.ServerConnection,c=i+s,u=a.url(c,e),d={body:JSON.stringify({raw:t}),method:"PUT"},h=await o(u,d,n);if(204!==h.status)throw new l(h)}}var a;t.SettingManager=o,function(e){e.url=function(e,t,n){const s=n?i.URLExt.objectToQueryString({ids_only:!0}):"";return`${i.URLExt.join(e,"api/settings",t)}${s}`}}(a||(a={}))},2195:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=WebSocket},5478:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TerminalConnection=void 0;const i=n(8920),s=n(5168),r=n(544),o=n(6914),a=n(4020);class l{constructor(e){var t;this._createSocket=()=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const e=this._name,t=this.serverSettings;let n=i.URLExt.join(t.wsUrl,"terminals","websocket",encodeURIComponent(e));const s=t.token;t.appendToken&&""!==s&&(n+=`?token=${encodeURIComponent(s)}`),this._ws=new t.WebSocket(n),this._ws.onmessage=this._onWSMessage,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose},this._onWSMessage=e=>{if(this._isDisposed)return;const t=JSON.parse(e.data);"disconnect"===t[0]&&this.dispose(),"connecting"!==this._connectionStatus?this._messageReceived.emit({type:t[0],content:t.slice(1)}):"setup"===t[0]&&this._updateConnectionStatus("connected")},this._onWSClose=e=>{console.warn(`Terminal websocket closed: ${e.code}`),this.isDisposed||this._reconnect()},this._connectionStatus="connecting",this._connectionStatusChanged=new r.Signal(this),this._isDisposed=!1,this._disposed=new r.Signal(this),this._messageReceived=new r.Signal(this),this._reconnectTimeout=null,this._ws=null,this._noOp=()=>{},this._reconnectLimit=7,this._reconnectAttempt=0,this._pendingMessages=[],this._name=e.model.name,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:o.ServerConnection.makeSettings(),this._createSocket()}get disposed(){return this._disposed}get messageReceived(){return this._messageReceived}get name(){return this._name}get model(){return{name:this._name}}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearSocket(),r.Signal.clearData(this))}send(e){this._sendMessage(e)}_sendMessage(e,t=!0){if(!this._isDisposed&&e.content)if("connected"===this.connectionStatus&&this._ws){const t=[e.type,...e.content];this._ws.send(JSON.stringify(t))}else{if(!t)throw new Error(`Could not send message: ${JSON.stringify(e)}`);this._pendingMessages.push(e)}}_sendPending(){for(;"connected"===this.connectionStatus&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}reconnect(){this._errorIfDisposed();const e=new s.PromiseDelegate,t=(n,i)=>{"connected"===i?(e.resolve(),this.connectionStatusChanged.disconnect(t,this)):"disconnected"===i&&(e.reject(new Error("Terminal connection disconnected")),this.connectionStatusChanged.disconnect(t,this))};return this.connectionStatusChanged.connect(t,this),this._reconnectAttempt=0,this._reconnect(),e.promise}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TerminalManager=void 0;const i=n(9033),s=n(544),r=n(6914),o=n(2918),a=n(4020),l=n(5478);class c extends o.BaseManager{constructor(e={}){var t;if(super(e),this._isReady=!1,this._names=[],this._terminalConnections=new Set,this._runningChanged=new s.Signal(this),this._connectionFailure=new s.Signal(this),!this.isAvailable())return this._ready=Promise.reject("Terminals unavailable"),void this._ready.catch((e=>{}));this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:TerminalManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._names.length=0,this._terminalConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}isAvailable(){return(0,a.isAvailable)()}connectTo(e){const t=new l.TerminalConnection({...e,serverSettings:this.serverSettings});return this._onStarted(t),this._names.includes(e.model.name)||this.refreshRunning().catch((()=>{})),t}running(){return this._models[Symbol.iterator]()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e){const t=await(0,a.startNew)(this.serverSettings,null==e?void 0:e.name,null==e?void 0:e.cwd);return await this.refreshRunning(),this.connectTo({model:t})}async shutdown(e){await(0,a.shutdownTerminal)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all(this._names.map((e=>(0,a.shutdownTerminal)(e,this.serverSettings)))),await this.refreshRunning()}async requestRunning(){var e,t;let n;try{n=await(0,a.listRunning)(this.serverSettings)}catch(n){throw(n instanceof r.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}if(this.isDisposed)return;const i=n.map((({name:e})=>e)).sort();i!==this._names&&(this._names=i,this._terminalConnections.forEach((e=>{i.includes(e.name)||e.dispose()})),this._runningChanged.emit(this._models))}_onStarted(e){this._terminalConnections.add(e),e.disposed.connect(this._onDisposed,this)}_onDisposed(e){this._terminalConnections.delete(e),this.refreshRunning().catch((()=>{}))}get _models(){return this._names.map((e=>({name:e})))}}t.TerminalManager=c,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}get ready(){return this.parentReady.then((()=>this._readyPromise))}async startNew(e){return Promise.reject(new Error("Not implemented in no-op Terminal Manager"))}connectTo(e){throw Error("Not implemented in no-op Terminal Manager")}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Terminal Manager"))}async requestRunning(){return Promise.resolve()}}}(c=t.TerminalManager||(t.TerminalManager={}))},4020:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shutdownTerminal=t.listRunning=t.startNew=t.isAvailable=t.TERMINAL_SERVICE_URL=void 0;const i=n(8920),s=n(2700);function r(){return"true"===String(i.PageConfig.getOption("terminalsAvailable")).toLowerCase()}var o;t.TERMINAL_SERVICE_URL="api/terminals",t.isAvailable=r,t.startNew=async function(e=s.ServerConnection.makeSettings(),n,r){o.errorIfNotAvailable();const a=i.URLExt.join(e.baseUrl,t.TERMINAL_SERVICE_URL),l={method:"POST",body:JSON.stringify({name:n,cwd:r})},c=await s.ServerConnection.makeRequest(a,l,e);if(200!==c.status)throw await s.ServerConnection.ResponseError.create(c);return await c.json()},t.listRunning=async function(e=s.ServerConnection.makeSettings()){o.errorIfNotAvailable();const n=i.URLExt.join(e.baseUrl,t.TERMINAL_SERVICE_URL),r=await s.ServerConnection.makeRequest(n,{},e);if(200!==r.status)throw await s.ServerConnection.ResponseError.create(r);const a=await r.json();if(!Array.isArray(a))throw new Error("Invalid terminal list");return a},t.shutdownTerminal=async function(e,n=s.ServerConnection.makeSettings()){var r;o.errorIfNotAvailable();const a=i.URLExt.join(n.baseUrl,t.TERMINAL_SERVICE_URL,e),l=await s.ServerConnection.makeRequest(a,{method:"DELETE"},n);if(404===l.status){const t=null!==(r=(await l.json()).message)&&void 0!==r?r:`The terminal session "${e}"" does not exist on the server`;console.warn(t)}else if(204!==l.status)throw await s.ServerConnection.ResponseError.create(l)},function(e){e.errorIfNotAvailable=function(){if(!r())throw new Error("Terminals Unavailable")}}(o||(o={}))},4468:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAvailable=void 0;const i=n(4020);Object.defineProperty(t,"isAvailable",{enumerable:!0,get:function(){return i.isAvailable}})},7523:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManager=void 0;const i=n(8920),s=n(5168),r=n(9033),o=n(544),a=n(2700),l=n(2918),c="@jupyterlab/services:UserManager#user";class u extends l.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._userChanged=new o.Signal(this),this._connectionFailure=new o.Signal(this),this._ready=this.requestUser().then((()=>{this.isDisposed||(this._isReady=!0)})).catch((e=>new Promise((()=>{})))),this._pollSpecs=new r.Poll({auto:!1,factory:()=>this.requestUser(),frequency:{interval:61e3,backoff:!0,max:3e5},name:c,standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this.ready.then((()=>{this._pollSpecs.start()}))}get isReady(){return this._isReady}get ready(){return this._ready}get identity(){return this._identity}get permissions(){return this._permissions}get userChanged(){return this._userChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshUser(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestUser(){if(this.isDisposed)return;const{baseUrl:e}=this.serverSettings,{makeRequest:t,ResponseError:n}=a.ServerConnection,r=i.URLExt.join(e,"api/me"),o=await t(r,{},this.serverSettings);if(200!==o.status)throw await n.create(o);const l={identity:this._identity,permissions:this._permissions},u=await o.json(),h=u.identity,{localStorage:p}=window,f=p.getItem(c);if(f&&(!h.initials||!h.color)){const e=JSON.parse(f);h.initials=h.initials||e.initials||h.name.substring(0,1),h.color=h.color||e.color||d.getRandomColor()}s.JSONExt.deepEqual(u,l)||(this._identity=h,this._permissions=u.permissions,p.setItem(c,JSON.stringify(h)),this._userChanged.emit(u))}}var d;t.UserManager=u,function(e){const t=["var(--jp-collaborator-color1)","var(--jp-collaborator-color2)","var(--jp-collaborator-color3)","var(--jp-collaborator-color4)","var(--jp-collaborator-color5)","var(--jp-collaborator-color6)","var(--jp-collaborator-color7)"];e.getRandomColor=()=>t[Math.floor(Math.random()*t.length)]}(d||(d={}))},8193:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateProperty=void 0,t.validateProperty=function(e,t,n,i=[]){if(!e.hasOwnProperty(t))throw Error(`Missing property '${t}'`);const s=e[t];if(void 0!==n){let e=!0;switch(n){case"array":e=Array.isArray(s);break;case"object":e=void 0!==s;break;default:e=typeof s===n}if(!e)throw new Error(`Property '${t}' is not of type '${n}'`);if(i.length>0){let e=!0;switch(n){case"string":case"number":case"boolean":e=i.includes(s);break;default:e=i.findIndex((e=>e===s))>=0}if(!e)throw new Error(`Property '${t}' is not one of the valid values ${JSON.stringify(i)}`)}}}},87:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkspaceManager=void 0;const i=n(8920),s=n(4116),r=n(2700);class o extends s.DataConnector{constructor(e={}){var t;super(),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings()}async fetch(e){const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:s,ResponseError:o}=r.ServerConnection,l=n+i,c=a.url(l,e),u=await s(c,{},t);if(200!==u.status)throw await o.create(u);return u.json()}async list(){const{serverSettings:e}=this,{baseUrl:t,appUrl:n}=e,{makeRequest:i,ResponseError:s}=r.ServerConnection,o=t+n,l=a.url(o,""),c=await i(l,{},e);if(200!==c.status)throw await s.create(c);return(await c.json()).workspaces}async remove(e){const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:s,ResponseError:o}=r.ServerConnection,l=n+i,c=a.url(l,e),u=await s(c,{method:"DELETE"},t);if(204!==u.status)throw await o.create(u)}async save(e,t){const{serverSettings:n}=this,{baseUrl:i,appUrl:s}=n,{makeRequest:o,ResponseError:l}=r.ServerConnection,c=i+s,u=a.url(c,e),d={body:JSON.stringify(t),method:"PUT"},h=await o(u,d,n);if(204!==h.status)throw await l.create(h)}}var a;t.WorkspaceManager=o,function(e){e.url=function(e,t){return i.URLExt.join(e,"api/workspaces",t)}}(a||(a={}))},5619:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityMonitor=void 0;const i=n(544);t.ActivityMonitor=class{constructor(e){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new i.Signal(this),e.signal.connect(this._onSignalFired,this),this._timeout=e.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(e){this._timeout=e}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,i.Signal.clearData(this))}_onSignalFired(e,t){clearTimeout(this._timer),this._sender=e,this._args=t,this._timer=setTimeout((()=>{this._activityStopped.emit({sender:this._sender,args:this._args})}),this._timeout)}}},8920:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(5619),t),s(n(8769),t),s(n(4612),t),s(n(9230),t),s(n(7034),t),s(n(902),t),s(n(6400),t),s(n(1718),t),s(n(8305),t)},8769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},4612:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MarkdownCodeBlocks=void 0,function(e){e.CODE_BLOCK_MARKER="```";const t=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class n{constructor(e){this.startLine=e,this.code="",this.endLine=-1}}e.MarkdownCodeBlock=n,e.isMarkdown=function(e){return t.indexOf(e)>-1},e.findMarkdownCodeBlocks=function(t){if(!t||""===t)return[];const i=t.split("\n"),s=[];let r=null;for(let t=0;te===t||i&&e===i))},e.isDisabled=function(t){const n=t.indexOf(":");let i="";return-1!==n&&(i=t.slice(0,n)),e.disabled.some((e=>e===t||i&&e===i))}}(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))},7034:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PathExt=void 0;const i=n(1023);!function(e){function t(e){return 0===e.indexOf("/")&&(e=e.slice(1)),e}e.join=function(...e){const n=i.posix.join(...e);return"."===n?"":t(n)},e.basename=function(e,t){return i.posix.basename(e,t)},e.dirname=function(e){const n=t(i.posix.dirname(e));return"."===n?"":n},e.extname=function(e){return i.posix.extname(e)},e.normalize=function(e){return""===e?"":t(i.posix.normalize(e))},e.resolve=function(...e){return t(i.posix.resolve(...e))},e.relative=function(e,n){return t(i.posix.relative(e,n))},e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e},e.removeSlash=t}(t.PathExt||(t.PathExt={}))},902:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalToPromise=void 0;const i=n(5168);t.signalToPromise=function(e,t){const n=new i.PromiseDelegate;function s(){e.disconnect(r)}function r(e,t){s(),n.resolve([e,t])}return e.connect(r),(null!=t?t:0)>0&&setTimeout((()=>{s(),n.reject(`Signal not emitted within ${t} ms.`)}),t),n.promise}},6400:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Text=void 0,function(e){const t="𝐚".length>1;e.jsIndexToCharIndex=function(e,n){if(t)return e;let i=e;for(let t=0;t+1=55296&&e<=56319){const e=n.charCodeAt(t+1);e>=56320&&e<=57343&&(i--,t++)}}return i},e.charIndexToJsIndex=function(e,n){if(t)return e;let i=e;for(let e=0;e+1=55296&&t<=56319){const t=n.charCodeAt(e+1);t>=56320&&t<=57343&&(i++,e++)}}return i},e.camelCase=function(e,t=!1){return e.replace(/^(\w)|[\s-_:]+(\w)/g,(function(e,n,i){return i?i.toUpperCase():t?n.toUpperCase():n.toLowerCase()}))},e.titleCase=function(e){return(e||"").toLowerCase().split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(" ")}}(t.Text||(t.Text={}))},1718:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Time=void 0;const n=[{name:"years",milliseconds:31536e6},{name:"months",milliseconds:2592e6},{name:"days",milliseconds:864e5},{name:"hours",milliseconds:36e5},{name:"minutes",milliseconds:6e4},{name:"seconds",milliseconds:1e3}];var i;(i=t.Time||(t.Time={})).formatHuman=function(e){const t=document.documentElement.lang||"en",i=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),s=new Date(e).getTime()-Date.now();for(let e of n){const t=Math.ceil(s/e.milliseconds);if(0!==t)return i.format(t,e.name)}return i.format(0,"seconds")},i.format=function(e){const t=document.documentElement.lang||"en";return new Intl.DateTimeFormat(t,{dateStyle:"short",timeStyle:"short"}).format(new Date(e))}},8305:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.URLExt=void 0;const s=n(1023),r=i(n(4846));!function(e){function t(e){if("undefined"!=typeof document&&document){const t=document.createElement("a");return t.href=e,t}return(0,r.default)(e)}function n(...e){let t=(0,r.default)(e[0],{});const n=""===t.protocol&&t.slashes;n&&(t=(0,r.default)(e[0],"https:"+e[0]));const i=`${n?"":t.protocol}${t.slashes?"//":""}${t.auth}${t.auth?"@":""}${t.host}`,o=s.posix.join(`${i&&"/"!==t.pathname[0]?"/":""}${t.pathname}`,...e.slice(1));return`${i}${"."===o?"":o}`}e.parse=t,e.getHostName=function(e){return(0,r.default)(e).hostname},e.normalize=function(e){return e&&t(e).toString()},e.join=n,e.encodeParts=function(e){return n(...e.split("/").map(encodeURIComponent))},e.objectToQueryString=function(e){const t=Object.keys(e).filter((e=>e.length>0));return t.length?"?"+t.map((t=>{const n=encodeURIComponent(String(e[t]));return t+(n?"="+n:"")})).join("&"):""},e.queryStringToObject=function(e){return e.replace(/^\?/,"").split("&").reduce(((e,t)=>{const[n,i]=t.split("=");return n.length>0&&(e[n]=decodeURIComponent(i||"")),e}),{})},e.isLocal=function(e){const{protocol:n}=t(e);return(!n||0!==e.toLowerCase().indexOf(n))&&0!==e.indexOf("/")}}(t.URLExt||(t.URLExt={}))},2845:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnector=void 0,t.DataConnector=class{async list(e){throw new Error("DataConnector#list method has not been implemented.")}async remove(e){throw new Error("DataConnector#remove method has not been implemented.")}async save(e,t){throw new Error("DataConnector#save method has not been implemented.")}}},4116:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(2845),t),s(n(3288),t),s(n(4803),t),s(n(6165),t),s(n(9329),t)},3288:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},4803:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RestorablePool=void 0;const i=n(5168),s=n(2571),r=n(544);var o;t.RestorablePool=class{constructor(e){this._added=new r.Signal(this),this._current=null,this._currentChanged=new r.Signal(this),this._hasRestored=!1,this._isDisposed=!1,this._objects=new Set,this._restore=null,this._restored=new i.PromiseDelegate,this._updated=new r.Signal(this),this.namespace=e.namespace}get added(){return this._added}get current(){return this._current}set current(e){this._current!==e&&null!==e&&this._objects.has(e)&&(this._current=e,this._currentChanged.emit(this._current))}get currentChanged(){return this._currentChanged}get isDisposed(){return this._isDisposed}get restored(){return this._restored.promise}get size(){return this._objects.size}get updated(){return this._updated}async add(e){var t,n;if(e.isDisposed){const t="A disposed object cannot be added.";throw console.warn(t,e),new Error(t)}if(this._objects.has(e)){const t="This object already exists in the pool.";throw console.warn(t,e),new Error(t)}if(this._objects.add(e),e.disposed.connect(this._onInstanceDisposed,this),!o.injectedProperty.get(e)){if(this._restore){const{connector:i}=this._restore,s=this._restore.name(e);if(s){const r=`${this.namespace}:${s}`,a=null===(n=(t=this._restore).args)||void 0===n?void 0:n.call(t,e);o.nameProperty.set(e,r),await i.save(r,{data:a})}}this._added.emit(e)}}dispose(){this.isDisposed||(this._current=null,this._isDisposed=!0,this._objects.clear(),r.Signal.clearData(this))}find(e){const t=this._objects.values();for(const n of t)if(e(n))return n}forEach(e){this._objects.forEach(e)}filter(e){const t=[];return this.forEach((n=>{e(n)&&t.push(n)})),t}inject(e){return o.injectedProperty.set(e,!0),this.add(e)}has(e){return this._objects.has(e)}async restore(e){if(this._hasRestored)throw new Error("This pool has already been restored.");this._hasRestored=!0;const{command:t,connector:n,registry:i,when:s}=e,r=this.namespace,o=s?[n.list(r)].concat(s):[n.list(r)];this._restore=e;const[a]=await Promise.all(o),l=await Promise.all(a.ids.map((async(e,s)=>{const r=a.values[s],o=r&&r.data;return void 0===o?n.remove(e):i.execute(t,o).catch((()=>n.remove(e)))})));return this._restored.resolve(),l}async save(e){var t,n;const i=o.injectedProperty.get(e);if(!this._restore||!this.has(e)||i)return;const{connector:s}=this._restore,r=this._restore.name(e),a=o.nameProperty.get(e),l=r?`${this.namespace}:${r}`:"";if(a&&a!==l&&await s.remove(a),o.nameProperty.set(e,l),l){const i=null===(n=(t=this._restore).args)||void 0===n?void 0:n.call(t,e);await s.save(l,{data:i})}a!==l&&this._updated.emit(e)}_onInstanceDisposed(e){if(this._objects.delete(e),e===this._current&&(this._current=null,this._currentChanged.emit(this._current)),o.injectedProperty.get(e))return;if(!this._restore)return;const{connector:t}=this._restore,n=o.nameProperty.get(e);n&&t.remove(n)}},function(e){e.injectedProperty=new s.AttachedProperty({name:"injected",create:()=>!1}),e.nameProperty=new s.AttachedProperty({name:"name",create:()=>""})}(o||(o={}))},6165:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StateDB=void 0;const i=n(544);class s{constructor(e={}){this._changed=new i.Signal(this);const{connector:t,transform:n}=e;this._connector=t||new s.Connector,this._ready=n?n.then((e=>{const{contents:t,type:n}=e;switch(n){case"cancel":default:return;case"clear":return this._clear();case"merge":return this._merge(t||{});case"overwrite":return this._overwrite(t||{})}})):Promise.resolve(void 0)}get changed(){return this._changed}async clear(){await this._ready,await this._clear()}async fetch(e){return await this._ready,this._fetch(e)}async list(e){return await this._ready,this._list(e)}async remove(e){await this._ready,await this._remove(e),this._changed.emit({id:e,type:"remove"})}async save(e,t){await this._ready,await this._save(e,t),this._changed.emit({id:e,type:"save"})}async toJSON(){await this._ready;const{ids:e,values:t}=await this._list();return t.reduce(((t,n,i)=>(t[e[i]]=n,t)),{})}async _clear(){await Promise.all((await this._list()).ids.map((e=>this._remove(e))))}async _fetch(e){const t=await this._connector.fetch(e);if(t)return JSON.parse(t).v}async _list(e=""){const{ids:t,values:n}=await this._connector.list(e);return{ids:t,values:n.map((e=>JSON.parse(e).v))}}async _merge(e){await Promise.all(Object.keys(e).map((t=>e[t]&&this._save(t,e[t]))))}async _overwrite(e){await this._clear(),await this._merge(e)}async _remove(e){return this._connector.remove(e)}async _save(e,t){return this._connector.save(e,JSON.stringify({v:t}))}}t.StateDB=s,function(e){e.Connector=class{constructor(){this._storage={}}async fetch(e){return this._storage[e]}async list(e=""){return Object.keys(this._storage).reduce(((t,n)=>(""!==e&&e!==n.split(":")[0]||(t.ids.push(n),t.values.push(this._storage[n])),t)),{ids:[],values:[]})}async remove(e){delete this._storage[e]}async save(e,t){this._storage[e]=t}}}(s=t.StateDB||(t.StateDB={}))},9329:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IStateDB=void 0;const i=n(5168);t.IStateDB=new i.Token("@jupyterlab/coreutils:IStateDB",'A service for the JupyterLab state database.\n Use this if you want to store data that will persist across page loads.\n See "state database" for more information.')},5168:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},4643:(e,t,n)=>{"use strict";n.r(t),n.d(t,{DisposableDelegate:()=>s,DisposableSet:()=>o,ObservableDisposableDelegate:()=>r,ObservableDisposableSet:()=>a});var i=n(544);class s{constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class r extends s{constructor(){super(...arguments),this._disposed=new i.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),i.Signal.clearData(this))}}class o{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(o||(o={}));class a extends o{constructor(){super(...arguments),this._disposed=new i.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),i.Signal.clearData(this))}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(a||(a={}))},9033:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Debouncer:()=>l,Poll:()=>o,RateLimiter:()=>a,Throttler:()=>c});var i,s=n(5168),r=n(544);class o{constructor(e){var t;this._disposed=new r.Signal(this),this._lingered=0,this._tick=new s.PromiseDelegate,this._ticked=new r.Signal(this),this._factory=e.factory,this._linger=null!==(t=e.linger)&&void 0!==t?t:i.DEFAULT_LINGER,this._standby=e.standby||i.DEFAULT_STANDBY,this._state={...i.DEFAULT_STATE,timestamp:(new Date).getTime()};const n=e.frequency||{},o=Math.max(n.interval||0,n.max||0,i.DEFAULT_FREQUENCY.max);this.frequency={...i.DEFAULT_FREQUENCY,...n,max:o},this.name=e.name||i.DEFAULT_NAME,"auto"in e&&!e.auto||setTimeout((()=>this.start()))}get disposed(){return this._disposed}get frequency(){return this._frequency}set frequency(e){if(this.isDisposed||s.JSONExt.deepEqual(e,this.frequency||{}))return;let{backoff:t,interval:n,max:i}=e;if(n=Math.round(n),i=Math.round(i),"number"==typeof t&&t<1)throw new Error("Poll backoff growth factor must be at least 1");if((n<0||n>i)&&n!==o.NEVER)throw new Error("Poll interval must be between 0 and max");if(i>o.MAX_INTERVAL&&i!==o.NEVER)throw new Error(`Max interval must be less than ${o.MAX_INTERVAL}`);this._frequency={backoff:t,interval:n,max:i}}get isDisposed(){return"disposed"===this.state.phase}get standby(){return this._standby}set standby(e){this.isDisposed||this.standby===e||(this._standby=e)}get state(){return this._state}get tick(){return this._tick.promise}get ticked(){return this._ticked}async*[Symbol.asyncIterator](){for(;!this.isDisposed;)yield this.state,await this.tick.catch((()=>{}))}dispose(){this.isDisposed||(this._state={...i.DISPOSED_STATE,timestamp:(new Date).getTime()},this._tick.promise.catch((e=>{})),this._tick.reject(new Error(`Poll (${this.name}) is disposed.`)),this._disposed.emit(void 0),r.Signal.clearData(this))}refresh(){return this.schedule({cancel:({phase:e})=>"refreshed"===e,interval:o.IMMEDIATE,phase:"refreshed"})}async schedule(e={}){if(this.isDisposed)return;if(e.cancel&&e.cancel(this.state))return;const t=this._tick,n=new s.PromiseDelegate,i={interval:this.frequency.interval,payload:null,phase:"standby",timestamp:(new Date).getTime(),...e};this._state=i,this._tick=n,clearTimeout(this._timeout),this._ticked.emit(this.state),t.resolve(this),await t.promise,i.interval!==o.NEVER?this._timeout=setTimeout((()=>{this.isDisposed||this.tick!==n.promise||this._execute()}),i.interval):this._timeout=void 0}start(){return this.schedule({cancel:({phase:e})=>"constructed"!==e&&"standby"!==e&&"stopped"!==e,interval:o.IMMEDIATE,phase:"started"})}stop(){return this.schedule({cancel:({phase:e})=>"stopped"===e,interval:o.NEVER,phase:"stopped"})}get hidden(){return i.hidden}_execute(){let e="function"==typeof this.standby?this.standby():this.standby;if("never"===e?e=!1:"when-hidden"===e&&(this.hidden?e=++this._lingered>this._linger:(this._lingered=0,e=!1)),e)return void this.schedule();const t=this.tick;this._factory(this.state).then((e=>{this.isDisposed||this.tick!==t||this.schedule({payload:e,phase:"rejected"===this.state.phase?"reconnected":"resolved"})})).catch((e=>{this.isDisposed||this.tick!==t||this.schedule({interval:i.sleep(this.frequency,this.state),payload:e,phase:"rejected"})}))}}!function(e){e.IMMEDIATE=0,e.MAX_INTERVAL=2147483647,e.NEVER=1/0}(o||(o={})),function(e){e.DEFAULT_BACKOFF=3,e.DEFAULT_FREQUENCY={backoff:!0,interval:1e3,max:3e4},e.DEFAULT_LINGER=1,e.DEFAULT_NAME="unknown",e.DEFAULT_STANDBY="when-hidden",e.DEFAULT_STATE={interval:o.NEVER,payload:null,phase:"constructed",timestamp:new Date(0).getTime()},e.DISPOSED_STATE={interval:o.NEVER,payload:null,phase:"disposed",timestamp:new Date(0).getTime()},e.sleep=function(t,n){const{backoff:i,interval:s,max:r}=t;if(s===o.NEVER)return s;const a=!0===i?e.DEFAULT_BACKOFF:!1===i?1:i,l=function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}(s,n.interval*a);return Math.min(r,l)},e.hidden="undefined"!=typeof document&&(document.addEventListener("visibilitychange",(()=>{e.hidden="hidden"===document.visibilityState})),document.addEventListener("pagehide",(()=>{e.hidden="hidden"===document.visibilityState})),"hidden"===document.visibilityState)}(i||(i={}));class a{constructor(e,t=500){this.args=void 0,this.payload=null,this.limit=t,this.poll=new o({auto:!1,factory:async()=>{const{args:t}=this;return this.args=void 0,e(...t)},frequency:{backoff:!1,interval:o.NEVER,max:o.NEVER},standby:"never"}),this.payload=new s.PromiseDelegate,this.poll.ticked.connect(((e,t)=>{const{payload:n}=this;return"resolved"===t.phase?(this.payload=new s.PromiseDelegate,void n.resolve(t.payload)):"rejected"===t.phase||"stopped"===t.phase?(this.payload=new s.PromiseDelegate,n.promise.catch((e=>{})),void n.reject(t.payload)):void 0}),this)}get isDisposed(){return null===this.payload}dispose(){this.isDisposed||(this.args=void 0,this.payload=null,this.poll.dispose())}async stop(){return this.poll.stop()}}class l extends a{invoke(...e){return this.args=e,this.poll.schedule({interval:this.limit,phase:"invoked"}),this.payload.promise}}class c extends a{constructor(e,t){super(e,"number"==typeof t?t:t&&t.limit),this._trailing=!1,"number"!=typeof t&&t&&"trailing"===t.edge&&(this._trailing=!0),this._interval=this._trailing?this.limit:o.IMMEDIATE}invoke(...e){const t="invoked"!==this.poll.state.phase;return(t||this._trailing)&&(this.args=e),t&&this.poll.schedule({interval:this._interval,phase:"invoked"}),this.payload.promise}}},2571:(e,t,n)=>{"use strict";n.r(t),n.d(t,{AttachedProperty:()=>i});class i{constructor(e){this._pid=s.nextPID(),this.name=e.name,this._create=e.create,this._coerce=e.coerce||null,this._compare=e.compare||null,this._changed=e.changed||null}get(e){let t,n=s.ensureMap(e);return t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e),t}set(e,t){let n,i=s.ensureMap(e);n=this._pid in i?i[this._pid]:i[this._pid]=this._createValue(e);let r=this._coerceValue(e,t);this._maybeNotify(e,n,i[this._pid]=r)}coerce(e){let t,n=s.ensureMap(e);t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e);let i=this._coerceValue(e,t);this._maybeNotify(e,t,n[this._pid]=i)}_createValue(e){return(0,this._create)(e)}_coerceValue(e,t){let n=this._coerce;return n?n(e,t):t}_compareValue(e,t){let n=this._compare;return n?n(e,t):e===t}_maybeNotify(e,t,n){let i=this._changed;i&&!this._compareValue(t,n)&&i(e,t,n)}}var s;!function(e){e.clearData=function(e){s.ownerData.delete(e)}}(i||(i={})),function(e){e.ownerData=new WeakMap,e.nextPID=(()=>{let e=0;return()=>`pid-${`${Math.random()}`.slice(2)}-${e++}`})(),e.ensureMap=function(t){let n=e.ownerData.get(t);return n||(n=Object.create(null),e.ownerData.set(t,n),n)}}(s||(s={}))},544:(e,t,n)=>{"use strict";var i,s,r;n.r(t),n.d(t,{Signal:()=>l,Stream:()=>c}),function(e){function t(e,t,n=0,i=-1){let s,r=e.length;if(0===r)return-1;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(i||(i={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(r||(r={}));var o,a=n(5168);class l{constructor(e){this.sender=e}connect(e,t){return o.connect(this,e,t)}disconnect(e,t){return o.disconnect(this,e,t)}emit(e){o.emit(this,e)}}!function(e){e.disconnectBetween=function(e,t){o.disconnectBetween(e,t)},e.disconnectSender=function(e){o.disconnectSender(e)},e.disconnectReceiver=function(e){o.disconnectReceiver(e)},e.disconnectAll=function(e){o.disconnectAll(e)},e.clearData=function(e){o.disconnectAll(e)},e.getExceptionHandler=function(){return o.exceptionHandler},e.setExceptionHandler=function(e){let t=o.exceptionHandler;return o.exceptionHandler=e,t}}(l||(l={}));class c extends l{constructor(){super(...arguments),this._pending=new a.PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new a.PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new a.PromiseDelegate}}!function(e){function t(e){let t=s.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,u(r.get(t))}u(t)}}function n(e){let t=r.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,u(s.get(t))}u(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let i=s.get(e.sender);if(i||(i=[],s.set(e.sender,i)),l(i,e,t,n))return!1;let o=n||t,a=r.get(o);a||(a=[],r.set(o,a));let c={signal:e,slot:t,thisArg:n};return i.push(c),a.push(c),!0},e.disconnect=function(e,t,n){n=n||void 0;let i=s.get(e.sender);if(!i||0===i.length)return!1;let o=l(i,e,t,n);if(!o)return!1;let a=n||t,c=r.get(a);return o.signal=null,u(i),u(c),!0},e.disconnectBetween=function(e,t){let n=s.get(e);if(!n||0===n.length)return;let i=r.get(t);if(i&&0!==i.length){for(const t of i)t.signal&&t.signal.sender===e&&(t.signal=null);u(n),u(i)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=s.get(e.sender);if(n&&0!==n.length)for(let i=0,s=n.length;i>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},6111:function(e){e.exports=function(){"use strict";function e(e,t){return e(t={exports:{}},t.exports),t.exports}var t=e((function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)})),n=e((function(e){var t=e.exports={version:"2.6.5"};"number"==typeof __e&&(__e=t)})),i=(n.version,function(e){return"object"==typeof e?null!==e:"function"==typeof e}),s=function(e){if(!i(e))throw TypeError(e+" is not an object!");return e},r=function(e){try{return!!e()}catch(e){return!0}},o=!r((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})),a=t.document,l=i(a)&&i(a.createElement),c=!o&&!r((function(){return 7!=Object.defineProperty((e="div",l?a.createElement(e):{}),"a",{get:function(){return 7}}).a;var e})),u=Object.defineProperty,d={f:o?Object.defineProperty:function(e,t,n){if(s(e),t=function(e,t){if(!i(e))return e;var n,s;if(t&&"function"==typeof(n=e.toString)&&!i(s=n.call(e)))return s;if("function"==typeof(n=e.valueOf)&&!i(s=n.call(e)))return s;if(!t&&"function"==typeof(n=e.toString)&&!i(s=n.call(e)))return s;throw TypeError("Can't convert object to primitive value")}(t,!0),s(n),c)try{return u(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},h=o?function(e,t,n){return d.f(e,t,function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}(1,n))}:function(e,t,n){return e[t]=n,e},p={}.hasOwnProperty,f=function(e,t){return p.call(e,t)},m=0,g=Math.random(),v=e((function(e){var i="__core-js_shared__",s=t[i]||(t[i]={});(e.exports=function(e,t){return s[e]||(s[e]=void 0!==t?t:{})})("versions",[]).push({version:n.version,mode:"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})})),_=v("native-function-to-string",Function.toString),y=e((function(e){var i=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++m+g).toString(36))}("src"),s="toString",r=(""+_).split(s);n.inspectSource=function(e){return _.call(e)},(e.exports=function(e,n,s,o){var a="function"==typeof s;a&&(f(s,"name")||h(s,"name",n)),e[n]!==s&&(a&&(f(s,i)||h(s,i,e[n]?""+e[n]:r.join(String(n)))),e===t?e[n]=s:o?e[n]?e[n]=s:h(e,n,s):(delete e[n],h(e,n,s)))})(Function.prototype,s,(function(){return"function"==typeof this&&this[i]||_.call(this)}))})),b=function(e,t,n){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,i){return e.call(t,n,i)};case 3:return function(n,i,s){return e.call(t,n,i,s)}}return function(){return e.apply(t,arguments)}},w="prototype",D=function(e,i,s){var r,o,a,l,c=e&D.F,u=e&D.G,d=e&D.S,p=e&D.P,f=e&D.B,m=u?t:d?t[i]||(t[i]={}):(t[i]||{})[w],g=u?n:n[i]||(n[i]={}),v=g[w]||(g[w]={});for(r in u&&(s=i),s)a=((o=!c&&m&&void 0!==m[r])?m:s)[r],l=f&&o?b(a,t):p&&"function"==typeof a?b(Function.call,a):a,m&&y(m,r,a,e&D.U),g[r]!=a&&h(g,r,l),p&&v[r]!=a&&(v[r]=a)};t.core=n,D.F=1,D.G=2,D.S=4,D.P=8,D.B=16,D.W=32,D.U=64,D.R=128;var x=D,C=Math.ceil,E=Math.floor,S=function(e){return isNaN(e=+e)?0:(e>0?E:C)(e)},A=(!1,function(e,t){var n,i,s=String(function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}(e)),r=S(t),o=s.length;return r<0||r>=o?void 0:(n=s.charCodeAt(r))<55296||n>56319||r+1===o||(i=s.charCodeAt(r+1))<56320||i>57343?n:i-56320+(n-55296<<10)+65536});x(x.P,"String",{codePointAt:function(e){return A(this,e)}}),n.String.codePointAt;var k=Math.max,M=Math.min,F=String.fromCharCode,I=String.fromCodePoint;x(x.S+x.F*(!!I&&1!=I.length),"String",{fromCodePoint:function(e){for(var t,n=arguments,i=[],s=arguments.length,r=0;s>r;){if(t=+n[r++],a=1114111,((o=S(o=t))<0?k(o+a,0):M(o,a))!==t)throw RangeError(t+" is not a valid code point");i.push(t<65536?F(t):F(55296+((t-=65536)>>10),t%1024+56320))}var o,a;return i.join("")}}),n.String.fromCodePoint;var O,P,B,R,T,L,j,N,z,U,q,W,H,K,$={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB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uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70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E88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF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\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},V={isSpaceSeparator:function(e){return"string"==typeof e&&$.Space_Separator.test(e)},isIdStartChar:function(e){return"string"==typeof e&&(e>="a"&&e<="z"||e>="A"&&e<="Z"||"$"===e||"_"===e||$.ID_Start.test(e))},isIdContinueChar:function(e){return"string"==typeof e&&(e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"$"===e||"_"===e||"‌"===e||"‍"===e||$.ID_Continue.test(e))},isDigit:function(e){return"string"==typeof e&&/[0-9]/.test(e)},isHexDigit:function(e){return"string"==typeof e&&/[0-9A-Fa-f]/.test(e)}};function J(e,t,n){var i=e[t];if(null!=i&&"object"==typeof i)if(Array.isArray(i))for(var s=0;s0;){var n=Y();if(!V.isHexDigit(n))throw re(X());e+=X()}return String.fromCodePoint(parseInt(e,16))}var ne={start:function(){if("eof"===j.type)throw oe();ie()},beforePropertyName:function(){switch(j.type){case"identifier":case"string":return N=j.value,void(P="afterPropertyName");case"punctuator":return void se();case"eof":throw oe()}},afterPropertyName:function(){if("eof"===j.type)throw oe();P="beforePropertyValue"},beforePropertyValue:function(){if("eof"===j.type)throw oe();ie()},beforeArrayValue:function(){if("eof"===j.type)throw oe();"punctuator"!==j.type||"]"!==j.value?ie():se()},afterPropertyValue:function(){if("eof"===j.type)throw oe();switch(j.value){case",":return void(P="beforePropertyName");case"}":se()}},afterArrayValue:function(){if("eof"===j.type)throw oe();switch(j.value){case",":return void(P="beforeArrayValue");case"]":se()}},end:function(){}};function ie(){var e;switch(j.type){case"punctuator":switch(j.value){case"{":e={};break;case"[":e=[]}break;case"null":case"boolean":case"numeric":case"string":e=j.value}if(void 0===z)z=e;else{var t=B[B.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,N,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(null!==e&&"object"==typeof e)B.push(e),P=Array.isArray(e)?"beforeArrayValue":"beforePropertyName";else{var n=B[B.length-1];P=null==n?"end":Array.isArray(n)?"afterArrayValue":"afterPropertyValue"}}function se(){B.pop();var e=B[B.length-1];P=null==e?"end":Array.isArray(e)?"afterArrayValue":"afterPropertyValue"}function re(e){return ce(void 0===e?"JSON5: invalid end of input at "+T+":"+L:"JSON5: invalid character '"+le(e)+"' at "+T+":"+L)}function oe(){return ce("JSON5: invalid end of input at "+T+":"+L)}function ae(){return ce("JSON5: invalid identifier character at "+T+":"+(L-=5))}function le(e){var t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(t[e])return t[e];if(e<" "){var n=e.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return e}function ce(e){var t=new SyntaxError(e);return t.lineNumber=T,t.columnNumber=L,t}return{parse:function(e,t){O=String(e),P="start",B=[],R=0,T=1,L=0,j=void 0,N=void 0,z=void 0;do{j=G(),ne[P]()}while("eof"!==j.type);return"function"==typeof t?J({"":z},"",t):z},stringify:function(e,t,n){var i,s,r,o=[],a="",l="";if(null==t||"object"!=typeof t||Array.isArray(t)||(n=t.space,r=t.quote,t=t.replacer),"function"==typeof t)s=t;else if(Array.isArray(t)){i=[];for(var c=0,u=t;c0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):"string"==typeof n&&(l=n.substr(0,10)),p("",{"":e});function p(e,t){var n=t[e];switch(null!=n&&("function"==typeof n.toJSON5?n=n.toJSON5(e):"function"==typeof n.toJSON&&(n=n.toJSON(e))),s&&(n=s.call(t,e,n)),n instanceof Number?n=Number(n):n instanceof String?n=String(n):n instanceof Boolean&&(n=n.valueOf()),n){case null:return"null";case!0:return"true";case!1:return"false"}return"string"==typeof n?f(n):"number"==typeof n?String(n):"object"==typeof n?Array.isArray(n)?function(e){if(o.indexOf(e)>=0)throw TypeError("Converting circular structure to JSON5");o.push(e);var t=a;a+=l;for(var n,i=[],s=0;s=0)throw TypeError("Converting circular structure to JSON5");o.push(e);var t=a;a+=l;for(var n,s,r=[],c=0,u=i||Object.keys(e);c{e.exports=function e(t,n,i){function s(o,a){if(!n[o]){if(!t[o]){if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[o]={exports:{}};t[o][0].call(c.exports,(function(e){return s(t[o][1][e]||e)}),c,c.exports,e,t,n,i)}return n[o].exports}for(var r=void 0,o=0;o=43)}})).catch((function(){return!1}))}(e).then((function(e){return h=e}))}function y(e){var t=p[e.name],n={};n.promise=new o((function(e,t){n.resolve=e,n.reject=t})),t.deferredOperations.push(n),t.dbReady?t.dbReady=t.dbReady.then((function(){return n.promise})):t.dbReady=n.promise}function b(e){var t=p[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function w(e,t){var n=p[e.name].deferredOperations.pop();if(n)return n.reject(t),n.promise}function D(e,t){return new o((function(n,i){if(p[e.name]=p[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return n(e.db);y(e),e.db.close()}var r=[e.name];t&&r.push(e.version);var o=s.open.apply(s,r);t&&(o.onupgradeneeded=function(t){var n=o.result;try{n.createObjectStore(e.storeName),t.oldVersion<=1&&n.createObjectStore(d)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),o.onerror=function(e){e.preventDefault(),i(o.error)},o.onsuccess=function(){var t=o.result;t.onversionchange=function(e){e.target.close()},n(t),b(e)}}))}function x(e){return D(e,!1)}function C(e){return D(e,!0)}function E(e,t){if(!e.db)return!0;var n=!e.db.objectStoreNames.contains(e.storeName),i=e.versione.db.version;if(i&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),s||n){if(n){var r=e.db.version+1;r>e.version&&(e.version=r)}return!0}return!1}function S(e){return r([v(atob(e.data))],{type:e.type})}function A(e){return e&&e.__local_forage_encoded_blob}function k(e){var t=this,n=t._initReady().then((function(){var e=p[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady}));return l(n,e,e),n}function M(e,t,n,i){void 0===i&&(i=1);try{var s=e.db.transaction(e.storeName,t);n(null,s)}catch(s){if(i>0&&(!e.db||"InvalidStateError"===s.name||"NotFoundError"===s.name))return o.resolve().then((function(){if(!e.db||"NotFoundError"===s.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),C(e)})).then((function(){return function(e){y(e);for(var t=p[e.name],n=t.forages,i=0;i>4,u[l++]=(15&i)<<4|s>>2,u[l++]=(3&s)<<6|63&r;return c}function Y(e){var t,n=new Uint8Array(e),i="";for(t=0;t>2],i+=I[(3&n[t])<<4|n[t+1]>>4],i+=I[(15&n[t+1])<<2|n[t+2]>>6],i+=I[63&n[t+2]];return n.length%3==2?i=i.substring(0,i.length-1)+"=":n.length%3==1&&(i=i.substring(0,i.length-2)+"=="),i}var X={serialize:function(e,t){var n="";if(e&&(n=J.call(e)),e&&("[object ArrayBuffer]"===n||e.buffer&&"[object ArrayBuffer]"===J.call(e.buffer))){var i,s=B;e instanceof ArrayBuffer?(i=e,s+=T):(i=e.buffer,"[object Int8Array]"===n?s+=j:"[object Uint8Array]"===n?s+=N:"[object Uint8ClampedArray]"===n?s+=z:"[object Int16Array]"===n?s+=U:"[object Uint16Array]"===n?s+=W:"[object Int32Array]"===n?s+=q:"[object Uint32Array]"===n?s+=H:"[object Float32Array]"===n?s+=K:"[object Float64Array]"===n?s+=$:t(new Error("Failed to get type for BinaryArray"))),t(s+Y(i))}else if("[object Blob]"===n){var r=new FileReader;r.onload=function(){var n=O+e.type+"~"+Y(this.result);t(B+L+n)},r.readAsArrayBuffer(e)}else try{t(JSON.stringify(e))}catch(n){console.error("Couldn't convert value into a JSON string: ",e),t(null,n)}},deserialize:function(e){if(e.substring(0,R)!==B)return JSON.parse(e);var t,n=e.substring(V),i=e.substring(R,V);if(i===L&&P.test(n)){var s=n.match(P);t=s[1],n=n.substring(s[0].length)}var o=G(n);switch(i){case T:return o;case L:return r([o],{type:t});case j:return new Int8Array(o);case N:return new Uint8Array(o);case z:return new Uint8ClampedArray(o);case U:return new Int16Array(o);case W:return new Uint16Array(o);case q:return new Int32Array(o);case H:return new Uint32Array(o);case K:return new Float32Array(o);case $:return new Float64Array(o);default:throw new Error("Unkown type: "+i)}},stringToBuffer:G,bufferToString:Y};function Z(e,t,n,i){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,i)}function Q(e,t,n,i,s,r){e.executeSql(n,i,s,(function(e,o){o.code===o.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[t.storeName],(function(e,a){a.rows.length?r(e,o):Z(e,t,(function(){e.executeSql(n,i,s,r)}),r)}),r):r(e,o)}),r)}function ee(e,t,n,i){var s=this;e=c(e);var r=new o((function(r,o){s.ready().then((function(){void 0===t&&(t=null);var a=t,l=s._dbInfo;l.serializer.serialize(t,(function(t,c){c?o(c):l.db.transaction((function(n){Q(n,l,"INSERT OR REPLACE INTO "+l.storeName+" (key, value) VALUES (?, ?)",[e,t],(function(){r(a)}),(function(e,t){o(t)}))}),(function(t){if(t.code===t.QUOTA_ERR){if(i>0)return void r(ee.apply(s,[e,a,n,i-1]));o(t)}}))}))})).catch(o)}));return a(r,n),r}var te={_driver:"webSQLStorage",_initStorage:function(e){var t=this,n={db:null};if(e)for(var i in e)n[i]="string"!=typeof e[i]?e[i].toString():e[i];var s=new o((function(e,i){try{n.db=openDatabase(n.name,String(n.version),n.description,n.size)}catch(e){return i(e)}n.db.transaction((function(s){Z(s,n,(function(){t._dbInfo=n,e()}),(function(e,t){i(t)}))}),i)}));return n.serializer=X,s},_support:"function"==typeof openDatabase,iterate:function(e,t){var n=this,i=new o((function(t,i){n.ready().then((function(){var s=n._dbInfo;s.db.transaction((function(n){Q(n,s,"SELECT * FROM "+s.storeName,[],(function(n,i){for(var r=i.rows,o=r.length,a=0;a '__WebKitDatabaseInfoTable__'",[],(function(n,i){for(var s=[],r=0;r0}var se={_driver:"localStorageWrapper",_initStorage:function(e){var t={};if(e)for(var n in e)t[n]=e[n];return t.keyPrefix=ne(e,this._defaultConfig),ie()?(this._dbInfo=t,t.serializer=X,o.resolve()):o.reject()},_support:function(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&!!localStorage.setItem}catch(e){return!1}}(),iterate:function(e,t){var n=this,i=n.ready().then((function(){for(var t=n._dbInfo,i=t.keyPrefix,s=i.length,r=localStorage.length,o=1,a=0;a=0;n--){var i=localStorage.key(n);0===i.indexOf(e)&&localStorage.removeItem(i)}}));return a(n,e),n},length:function(e){var t=this.keys().then((function(e){return e.length}));return a(t,e),t},key:function(e,t){var n=this,i=n.ready().then((function(){var t,i=n._dbInfo;try{t=localStorage.key(e)}catch(e){t=null}return t&&(t=t.substring(i.keyPrefix.length)),t}));return a(i,t),i},keys:function(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo,n=localStorage.length,i=[],s=0;s=0;t--){var n=localStorage.key(t);0===n.indexOf(e)&&localStorage.removeItem(n)}})):o.reject("Invalid arguments"),a(i,t),i}},re=function(e,t){for(var n=e.length,i=0;i{"use strict";function t(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function n(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}e.exports=function(e,i){i||(i={});var s={bools:{},strings:{},unknownFn:null};"function"==typeof i.unknown&&(s.unknownFn=i.unknown),"boolean"==typeof i.boolean&&i.boolean?s.allBools=!0:[].concat(i.boolean).filter(Boolean).forEach((function(e){s.bools[e]=!0}));var r={};function o(e){return r[e].some((function(e){return s.bools[e]}))}Object.keys(i.alias||{}).forEach((function(e){r[e]=[].concat(i.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(i.string).filter(Boolean).forEach((function(e){s.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){s.strings[e]=!0}))}));var a=i.default||{},l={_:[]};function c(e,t,i){for(var r=e,o=0;o=2&&(n=n.slice(2)):v(s)?n=i[4]:s?r&&(n=n.slice(2)):a>=2&&v(t.protocol)&&(n=i[4]),{protocol:s,slashes:r||v(s),slashesCount:a,rest:n}}function y(e,t,n){if(e=(e=p(e)).replace(l,""),!(this instanceof y))return new y(e,t,n);var s,r,o,c,u,h,m=f.slice(),b=typeof t,w=this,D=0;for("object"!==b&&"string"!==b&&(n=t,t=null),n&&"function"!=typeof n&&(n=a.parse),s=!(r=_(e||"",t=g(t))).protocol&&!r.slashes,w.slashes=r.slashes||s&&t.slashes,w.protocol=r.protocol||t.protocol||"",e=r.rest,("file:"===r.protocol&&(2!==r.slashesCount||d.test(e))||!r.slashes&&(r.protocol||r.slashesCount<2||!v(w.protocol)))&&(m[3]=[/(.*)/,"pathname"]);D=0?e.slice(0,t):e}C.prototype.addEventListener=function(e,t){"function"==typeof t&&(Array.isArray(this.listeners[e])||(this.listeners[e]=[]),0===function(e,t){void 0===e&&(e=[]);var n=[];return e.forEach((function(e){t(e)&&n.push(e)})),n}(this.listeners[e],(function(e){return e===t})).length&&this.listeners[e].push(t))},C.prototype.removeEventListener=function(e,t){var n=this.listeners[e];this.listeners[e]=x(n,(function(e){return e===t}))},C.prototype.dispatchEvent=function(e){for(var t=this,n=[],i=arguments.length-1;i-- >0;)n[i]=arguments[i+1];var s=e.type,r=this.listeners[s];return!!Array.isArray(r)&&(r.forEach((function(i){n.length>0?i.apply(t,n):i.call(t,e)})),!0)};var S=function(){this.urlMap={}};S.prototype.attachWebSocket=function(e,t){var n=E(t),i=this.urlMap[n];if(i&&i.server&&-1===i.websockets.indexOf(e))return i.websockets.push(e),i.server},S.prototype.addMembershipToRoom=function(e,t){var n=this.urlMap[E(e.url)];n&&n.server&&-1!==n.websockets.indexOf(e)&&(n.roomMemberships[t]||(n.roomMemberships[t]=[]),n.roomMemberships[t].push(e))},S.prototype.attachServer=function(e,t){var n=E(t);if(!this.urlMap[n])return this.urlMap[n]={server:e,websockets:[],roomMemberships:{}},e},S.prototype.serverLookup=function(e){var t=E(e),n=this.urlMap[t];if(n)return n.server},S.prototype.websocketsLookup=function(e,t,n){var i,s=E(e),r=this.urlMap[s];return i=r?r.websockets:[],t&&(i=r.roomMemberships[t]||[]),n?i.filter((function(e){return e!==n})):i},S.prototype.removeServer=function(e){delete this.urlMap[E(e)]},S.prototype.removeWebSocket=function(e,t){var n=E(t),i=this.urlMap[n];i&&(i.websockets=x(i.websockets,(function(t){return t===e})))},S.prototype.removeMembershipFromRoom=function(e,t){var n=this.urlMap[E(e.url)],i=n.roomMemberships[t];n&&null!==i&&(n.roomMemberships[t]=x(i,(function(t){return t===e})))};var A=new S,k={CLOSE_NORMAL:1e3,CLOSE_GOING_AWAY:1001,CLOSE_PROTOCOL_ERROR:1002,CLOSE_UNSUPPORTED:1003,CLOSE_NO_STATUS:1005,CLOSE_ABNORMAL:1006,UNSUPPORTED_DATA:1007,POLICY_VIOLATION:1008,CLOSE_TOO_LARGE:1009,MISSING_EXTENSION:1010,INTERNAL_ERROR:1011,SERVICE_RESTART:1012,TRY_AGAIN_LATER:1013,TLS_HANDSHAKE:1015},M={CONSTRUCTOR_ERROR:"Failed to construct 'WebSocket':",CLOSE_ERROR:"Failed to execute 'close' on 'WebSocket':",EVENT:{CONSTRUCT:"Failed to construct 'Event':",MESSAGE:"Failed to construct 'MessageEvent':",CLOSE:"Failed to construct 'CloseEvent':"}},F=function(){};F.prototype.stopPropagation=function(){},F.prototype.stopImmediatePropagation=function(){},F.prototype.initEvent=function(e,t,n){void 0===e&&(e="undefined"),void 0===t&&(t=!1),void 0===n&&(n=!1),this.type=""+e,this.bubbles=Boolean(t),this.cancelable=Boolean(n)};var I=function(e){function t(t,n){if(void 0===n&&(n={}),e.call(this),!t)throw new TypeError(M.EVENT_ERROR+" 1 argument required, but only 0 present.");if("object"!=typeof n)throw new TypeError(M.EVENT_ERROR+" parameter 2 ('eventInitDict') is not an object.");var i=n.bubbles,s=n.cancelable;this.type=""+t,this.timeStamp=Date.now(),this.target=null,this.srcElement=null,this.returnValue=!0,this.isTrusted=!1,this.eventPhase=0,this.defaultPrevented=!1,this.currentTarget=null,this.cancelable=!!s&&Boolean(s),this.cancelBubble=!1,this.bubbles=!!i&&Boolean(i)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(F),O=function(e){function t(t,n){if(void 0===n&&(n={}),e.call(this),!t)throw new TypeError(M.EVENT.MESSAGE+" 1 argument required, but only 0 present.");if("object"!=typeof n)throw new TypeError(M.EVENT.MESSAGE+" parameter 2 ('eventInitDict') is not an object");var i=n.bubbles,s=n.cancelable,r=n.data,o=n.origin,a=n.lastEventId,l=n.ports;this.type=""+t,this.timeStamp=Date.now(),this.target=null,this.srcElement=null,this.returnValue=!0,this.isTrusted=!1,this.eventPhase=0,this.defaultPrevented=!1,this.currentTarget=null,this.cancelable=!!s&&Boolean(s),this.canncelBubble=!1,this.bubbles=!!i&&Boolean(i),this.origin=""+o,this.ports=void 0===l?null:l,this.data=void 0===r?null:r,this.lastEventId=""+(a||"")}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(F),P=function(e){function t(t,n){if(void 0===n&&(n={}),e.call(this),!t)throw new TypeError(M.EVENT.CLOSE+" 1 argument required, but only 0 present.");if("object"!=typeof n)throw new TypeError(M.EVENT.CLOSE+" parameter 2 ('eventInitDict') is not an object");var i=n.bubbles,s=n.cancelable,r=n.code,o=n.reason,a=n.wasClean;this.type=""+t,this.timeStamp=Date.now(),this.target=null,this.srcElement=null,this.returnValue=!0,this.isTrusted=!1,this.eventPhase=0,this.defaultPrevented=!1,this.currentTarget=null,this.cancelable=!!s&&Boolean(s),this.cancelBubble=!1,this.bubbles=!!i&&Boolean(i),this.code="number"==typeof r?parseInt(r,10):0,this.reason=""+(o||""),this.wasClean=!!a&&Boolean(a)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(F);function B(e){var t=e.type,n=e.target,i=new I(t);return n&&(i.target=n,i.srcElement=n,i.currentTarget=n),i}function R(e){var t=e.type,n=e.origin,i=e.data,s=e.target,r=new O(t,{data:i,origin:n});return s&&(r.target=s,r.srcElement=s,r.currentTarget=s),r}function T(e){var t=e.code,n=e.reason,i=e.type,s=e.target,r=e.wasClean;r||(r=t===k.CLOSE_NORMAL||t===k.CLOSE_NO_STATUS);var o=new P(i,{code:t,reason:n,wasClean:r});return s&&(o.target=s,o.srcElement=s,o.currentTarget=s),o}function L(e,t,n){e.readyState=U.CLOSING;var i=A.serverLookup(e.url),s=T({type:"close",target:e.target,code:t,reason:n});w((function(){A.removeWebSocket(e,e.url),e.readyState=U.CLOSED,e.dispatchEvent(s),i&&i.dispatchEvent(s,i)}),e)}function j(e){return"[object Blob]"===Object.prototype.toString.call(e)||e instanceof ArrayBuffer||(e=String(e)),e}var N=new WeakMap;function z(e){if(N.has(e))return N.get(e);var t=new Proxy(e,{get:function(n,i){if("close"===i)return function(e){void 0===e&&(e={});var n=e.code||k.CLOSE_NORMAL,i=e.reason||"";L(t,n,i)};if("send"===i)return function(t){t=j(t),e.dispatchEvent(R({type:"message",data:t,origin:this.url,target:e}))};var s=function(e){return"message"===e?"server::"+e:e};return"on"===i?function(t,n){e.addEventListener(s(t),n)}:"off"===i?function(t,n){e.removeEventListener(s(t),n)}:"target"===i?e:n[i]}});return N.set(e,t),t}var U=function(e){function t(n,i){e.call(this),this._onopen=null,this._onmessage=null,this._onerror=null,this._onclose=null,this.url=function(e){var t=new b(e),n=t.pathname,i=t.protocol,s=t.hash;if(!e)throw new TypeError(M.CONSTRUCTOR_ERROR+" 1 argument required, but only 0 present.");if(n||(t.pathname="/"),""===i)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The URL '"+t.toString()+"' is invalid.");if("ws:"!==i&&"wss:"!==i)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The URL's scheme must be either 'ws' or 'wss'. '"+i+"' is not allowed.");if(""!==s)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The URL contains a fragment identifier ('"+s+"'). Fragment identifiers are not allowed in WebSocket URLs.");return t.toString()}(n),i=function(e){if(void 0===e&&(e=[]),!Array.isArray(e)&&"string"!=typeof e)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The subprotocol '"+e.toString()+"' is invalid.");"string"==typeof e&&(e=[e]);var t=e.map((function(e){return{count:1,protocol:e}})).reduce((function(e,t){return e[t.protocol]=(e[t.protocol]||0)+t.count,e}),{}),n=Object.keys(t).filter((function(e){return t[e]>1}));if(n.length>0)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The subprotocol '"+n[0]+"' is duplicated.");return e}(i),this.protocol=i[0]||"",this.binaryType="blob",this.readyState=t.CONNECTING;var s=z(this),r=A.attachWebSocket(s,this.url);w((function(){if(r)if(r.options.verifyClient&&"function"==typeof r.options.verifyClient&&!r.options.verifyClient())this.readyState=t.CLOSED,D("error","WebSocket connection to '"+this.url+"' failed: HTTP Authentication failed; no valid credentials available"),A.removeWebSocket(s,this.url),this.dispatchEvent(B({type:"error",target:this})),this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL}));else{if(r.options.selectProtocol&&"function"==typeof r.options.selectProtocol){var e=r.options.selectProtocol(i),n=""!==e,o=-1!==i.indexOf(e);if(n&&!o)return this.readyState=t.CLOSED,D("error","WebSocket connection to '"+this.url+"' failed: Invalid Sub-Protocol"),A.removeWebSocket(s,this.url),this.dispatchEvent(B({type:"error",target:this})),void this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL}));this.protocol=e}this.readyState=t.OPEN,this.dispatchEvent(B({type:"open",target:this})),r.dispatchEvent(B({type:"connection"}),s)}else this.readyState=t.CLOSED,this.dispatchEvent(B({type:"error",target:this})),this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL})),D("error","WebSocket connection to '"+this.url+"' failed")}),this)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={onopen:{},onmessage:{},onclose:{},onerror:{}};return n.onopen.get=function(){return this._onopen},n.onmessage.get=function(){return this._onmessage},n.onclose.get=function(){return this._onclose},n.onerror.get=function(){return this._onerror},n.onopen.set=function(e){this.removeEventListener("open",this._onopen),this._onopen=e,this.addEventListener("open",e)},n.onmessage.set=function(e){this.removeEventListener("message",this._onmessage),this._onmessage=e,this.addEventListener("message",e)},n.onclose.set=function(e){this.removeEventListener("close",this._onclose),this._onclose=e,this.addEventListener("close",e)},n.onerror.set=function(e){this.removeEventListener("error",this._onerror),this._onerror=e,this.addEventListener("error",e)},t.prototype.send=function(e){var n=this;if(this.readyState===t.CLOSING||this.readyState===t.CLOSED)throw new Error("WebSocket is already in CLOSING or CLOSED state");var i=R({type:"server::message",origin:this.url,data:j(e)}),s=A.serverLookup(this.url);s&&w((function(){n.dispatchEvent(i,e)}),s)},t.prototype.close=function(e,n){if(void 0!==e&&("number"!=typeof e||1e3!==e&&(e<3e3||e>4999)))throw new TypeError(M.CLOSE_ERROR+" The code must be either 1000, or between 3000 and 4999. "+e+" is neither.");if(void 0!==n&&(i=n,s=encodeURIComponent(i).match(/%[89ABab]/g),i.length+(s?s.length:0)>123))throw new SyntaxError(M.CLOSE_ERROR+" The message must not be greater than 123 bytes.");var i,s;if(this.readyState!==t.CLOSING&&this.readyState!==t.CLOSED){var r=z(this);this.readyState===t.CONNECTING?function(e,t,n){e.readyState=U.CLOSING;var i=A.serverLookup(e.url),s=T({type:"close",target:e.target,code:t,reason:n,wasClean:!1}),r=B({type:"error",target:e.target});w((function(){A.removeWebSocket(e,e.url),e.readyState=U.CLOSED,e.dispatchEvent(r),e.dispatchEvent(s),i&&i.dispatchEvent(s,i)}),e)}(r,e||k.CLOSE_ABNORMAL,n):L(r,e||k.CLOSE_NO_STATUS,n)}},Object.defineProperties(t.prototype,n),t}(C);U.CONNECTING=0,U.prototype.CONNECTING=U.CONNECTING,U.OPEN=1,U.prototype.OPEN=U.OPEN,U.CLOSING=2,U.prototype.CLOSING=U.CLOSING,U.CLOSED=3,U.prototype.CLOSED=U.CLOSED;var q=function(e){function t(n,i){var s=this;void 0===n&&(n="socket.io"),void 0===i&&(i=""),e.call(this),this.binaryType="blob";var r=new b(n);r.pathname||(r.pathname="/"),this.url=r.toString(),this.readyState=t.CONNECTING,this.protocol="",this.target=this,"string"==typeof i||"object"==typeof i&&null!==i?this.protocol=i:Array.isArray(i)&&i.length>0&&(this.protocol=i[0]);var o=A.attachWebSocket(this,this.url);w((function(){o?(this.readyState=t.OPEN,o.dispatchEvent(B({type:"connection"}),o,this),o.dispatchEvent(B({type:"connect"}),o,this),this.dispatchEvent(B({type:"connect",target:this}))):(this.readyState=t.CLOSED,this.dispatchEvent(B({type:"error",target:this})),this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL})),D("error","Socket.io connection to '"+this.url+"' failed"))}),this),this.addEventListener("close",(function(e){s.dispatchEvent(T({type:"disconnect",target:e.target,code:e.code}))}))}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={broadcast:{}};return t.prototype.close=function(){if(this.readyState===t.OPEN){var e=A.serverLookup(this.url);return A.removeWebSocket(this,this.url),this.readyState=t.CLOSED,this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL})),e&&e.dispatchEvent(T({type:"disconnect",target:this,code:k.CLOSE_NORMAL}),e),this}},t.prototype.disconnect=function(){return this.close()},t.prototype.emit=function(e){for(var n=[],i=arguments.length-1;i-- >0;)n[i]=arguments[i+1];if(this.readyState!==t.OPEN)throw new Error("SocketIO is already in CLOSING or CLOSED state");var s=R({type:e,origin:this.url,data:n}),r=A.serverLookup(this.url);return r&&r.dispatchEvent.apply(r,[s].concat(n)),this},t.prototype.send=function(e){return this.emit("message",e),this},n.broadcast.get=function(){if(this.readyState!==t.OPEN)throw new Error("SocketIO is already in CLOSING or CLOSED state");var e=this,n=A.serverLookup(this.url);if(!n)throw new Error("SocketIO can not find a server at the specified URL ("+this.url+")");return{emit:function(t,i){return n.emit(t,i,{websockets:A.websocketsLookup(e.url,null,e)}),e},to:function(t){return n.to(t,e)},in:function(t){return n.in(t,e)}}},t.prototype.on=function(e,t){return this.addEventListener(e,t),this},t.prototype.off=function(e,t){this.removeEventListener(e,t)},t.prototype.hasListeners=function(e){var t=this.listeners[e];return!!Array.isArray(t)&&!!t.length},t.prototype.join=function(e){A.addMembershipToRoom(this,e)},t.prototype.leave=function(e){A.removeMembershipFromRoom(this,e)},t.prototype.to=function(e){return this.broadcast.to(e)},t.prototype.in=function(){return this.to.apply(null,arguments)},t.prototype.dispatchEvent=function(e){for(var t=this,n=[],i=arguments.length-1;i-- >0;)n[i]=arguments[i+1];var s=e.type,r=this.listeners[s];if(!Array.isArray(r))return!1;r.forEach((function(i){n.length>0?i.apply(t,n):i.call(t,e.data?e.data:e)}))},Object.defineProperties(t.prototype,n),t}(C);q.CONNECTING=0,q.OPEN=1,q.CLOSING=2,q.CLOSED=3;var W=function(e,t){return new q(e,t)};W.connect=function(e,t){return W(e,t)};function H(){return"undefined"!=typeof window?window:"object"==typeof process&&"object"==typeof n.g?n.g:this}var K={mock:!0,verifyClient:null,selectProtocol:null},$=function(e){function t(t,n){void 0===n&&(n=K),e.call(this);var i=new b(t);if(i.pathname||(i.pathname="/"),this.url=i.toString(),this.originalWebSocket=null,!A.attachServer(this,this.url))throw this.dispatchEvent(B({type:"error"})),new Error("A mock server is already listening on this url");this.options=Object.assign({},K,n),this.options.mock&&this.mockWebsocket()}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.mockWebsocket=function(){var e=H();this.originalWebSocket=e.WebSocket,e.WebSocket=U},t.prototype.restoreWebsocket=function(){var e=H();null!==this.originalWebSocket&&(e.WebSocket=this.originalWebSocket),this.originalWebSocket=null},t.prototype.stop=function(e){void 0===e&&(e=function(){}),this.options.mock&&this.restoreWebsocket(),A.removeServer(this.url),"function"==typeof e&&e()},t.prototype.on=function(e,t){this.addEventListener(e,t)},t.prototype.off=function(e,t){this.removeEventListener(e,t)},t.prototype.close=function(e){void 0===e&&(e={});var t=e.code,n=e.reason,i=e.wasClean,s=A.websocketsLookup(this.url);A.removeServer(this.url),s.forEach((function(e){e.readyState=U.CLOSED,e.dispatchEvent(T({type:"close",target:e.target,code:t||k.CLOSE_NORMAL,reason:n||"",wasClean:i}))})),this.dispatchEvent(T({type:"close"}),this)},t.prototype.emit=function(e,t,n){var i=this;void 0===n&&(n={});var s,r=n.websockets;r||(r=A.websocketsLookup(this.url)),"object"!=typeof n||arguments.length>3?(t=Array.prototype.slice.call(arguments,1,arguments.length),s=t.map((function(e){return j(e)}))):s=j(t),r.forEach((function(n){var r=n instanceof q?t:s;Array.isArray(r)?n.dispatchEvent.apply(n,[R({type:e,data:r,origin:i.url,target:n.target})].concat(r)):n.dispatchEvent(R({type:e,data:r,origin:i.url,target:n.target}))}))},t.prototype.clients=function(){return A.websocketsLookup(this.url)},t.prototype.to=function(e,t,n){var i=this;void 0===n&&(n=[]);var s=this,r=n.concat(A.websocketsLookup(this.url,e,t)).reduce((function(e,t){return e.indexOf(t)>-1?e:e.concat(t)}),[]);return{to:function(e,t){return i.to.call(i,e,t,r)},emit:function(e,t){s.emit(e,t,{websockets:r})}}},t.prototype.in=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return this.to.apply(null,e)},t.prototype.simulate=function(e){var t=A.websocketsLookup(this.url);"error"===e&&t.forEach((function(e){e.readyState=U.CLOSED,e.dispatchEvent(B({type:"error",target:e.target}))}))},t}(C);$.of=function(e){return new $(e)};var V=$,J=U,G=W;e.Server=V,e.WebSocket=J,e.SocketIO=G,Object.defineProperty(e,"__esModule",{value:!0})}(t)},1023:e=>{"use strict";function t(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function n(e,t){for(var n,i="",s=0,r=-1,o=0,a=0;a<=e.length;++a){if(a2){var l=i.lastIndexOf("/");if(l!==i.length-1){-1===l?(i="",s=0):s=(i=i.slice(0,l)).length-1-i.lastIndexOf("/"),r=a,o=0;continue}}else if(2===i.length||1===i.length){i="",s=0,r=a,o=0;continue}t&&(i.length>0?i+="/..":i="..",s=2)}else i.length>0?i+="/"+e.slice(r+1,a):i=e.slice(r+1,a),s=a-r-1;r=a,o=0}else 46===n&&-1!==o?++o:o=-1}return i}var i={resolve:function(){for(var e,i="",s=!1,r=arguments.length-1;r>=-1&&!s;r--){var o;r>=0?o=arguments[r]:(void 0===e&&(e=process.cwd()),o=e),t(o),0!==o.length&&(i=o+"/"+i,s=47===o.charCodeAt(0))}return i=n(i,!s),s?i.length>0?"/"+i:"/":i.length>0?i:"."},normalize:function(e){if(t(e),0===e.length)return".";var i=47===e.charCodeAt(0),s=47===e.charCodeAt(e.length-1);return 0!==(e=n(e,!i)).length||i||(e="."),e.length>0&&s&&(e+="/"),i?"/"+e:e},isAbsolute:function(e){return t(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,n=0;n0&&(void 0===e?e=s:e+="/"+s)}return void 0===e?".":i.normalize(e)},relative:function(e,n){if(t(e),t(n),e===n)return"";if((e=i.resolve(e))===(n=i.resolve(n)))return"";for(var s=1;sc){if(47===n.charCodeAt(a+d))return n.slice(a+d+1);if(0===d)return n.slice(a+d)}else o>c&&(47===e.charCodeAt(s+d)?u=d:0===d&&(u=0));break}var h=e.charCodeAt(s+d);if(h!==n.charCodeAt(a+d))break;47===h&&(u=d)}var p="";for(d=s+u+1;d<=r;++d)d!==r&&47!==e.charCodeAt(d)||(0===p.length?p+="..":p+="/..");return p.length>0?p+n.slice(a+u):(a+=u,47===n.charCodeAt(a)&&++a,n.slice(a))},_makeLong:function(e){return e},dirname:function(e){if(t(e),0===e.length)return".";for(var n=e.charCodeAt(0),i=47===n,s=-1,r=!0,o=e.length-1;o>=1;--o)if(47===(n=e.charCodeAt(o))){if(!r){s=o;break}}else r=!1;return-1===s?i?"/":".":i&&1===s?"//":e.slice(0,s)},basename:function(e,n){if(void 0!==n&&"string"!=typeof n)throw new TypeError('"ext" argument must be a string');t(e);var i,s=0,r=-1,o=!0;if(void 0!==n&&n.length>0&&n.length<=e.length){if(n.length===e.length&&n===e)return"";var a=n.length-1,l=-1;for(i=e.length-1;i>=0;--i){var c=e.charCodeAt(i);if(47===c){if(!o){s=i+1;break}}else-1===l&&(o=!1,l=i+1),a>=0&&(c===n.charCodeAt(a)?-1==--a&&(r=i):(a=-1,r=l))}return s===r?r=l:-1===r&&(r=e.length),e.slice(s,r)}for(i=e.length-1;i>=0;--i)if(47===e.charCodeAt(i)){if(!o){s=i+1;break}}else-1===r&&(o=!1,r=i+1);return-1===r?"":e.slice(s,r)},extname:function(e){t(e);for(var n=-1,i=0,s=-1,r=!0,o=0,a=e.length-1;a>=0;--a){var l=e.charCodeAt(a);if(47!==l)-1===s&&(r=!1,s=a+1),46===l?-1===n?n=a:1!==o&&(o=1):-1!==n&&(o=-1);else if(!r){i=a+1;break}}return-1===n||-1===s||0===o||1===o&&n===s-1&&n===i+1?"":e.slice(n,s)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var n=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+i:n+"/"+i:i}(0,e)},parse:function(e){t(e);var n={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return n;var i,s=e.charCodeAt(0),r=47===s;r?(n.root="/",i=1):i=0;for(var o=-1,a=0,l=-1,c=!0,u=e.length-1,d=0;u>=i;--u)if(47!==(s=e.charCodeAt(u)))-1===l&&(c=!1,l=u+1),46===s?-1===o?o=u:1!==d&&(d=1):-1!==o&&(d=-1);else if(!c){a=u+1;break}return-1===o||-1===l||0===d||1===d&&o===l-1&&o===a+1?-1!==l&&(n.base=n.name=0===a&&r?e.slice(1,l):e.slice(a,l)):(0===a&&r?(n.name=e.slice(1,o),n.base=e.slice(1,l)):(n.name=e.slice(a,o),n.base=e.slice(a,l)),n.ext=e.slice(o,l)),a>0?n.dir=e.slice(0,a-1):r&&(n.dir="/"),n},sep:"/",delimiter:":",win32:null,posix:null};i.posix=i,e.exports=i},7375:(e,t)=>{"use strict";var n=Object.prototype.hasOwnProperty;function i(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function s(e){try{return encodeURIComponent(e)}catch(e){return null}}t.stringify=function(e,t){t=t||"";var i,r,o=[];for(r in"string"!=typeof t&&(t="?"),e)if(n.call(e,r)){if((i=e[r])||null!=i&&!isNaN(i)||(i=""),r=s(r),i=s(i),null===r||null===i)continue;o.push(r+"="+i)}return o.length?t+o.join("&"):""},t.parse=function(e){for(var t,n=/([^=?#&]+)=?([^&]*)/g,s={};t=n.exec(e);){var r=i(t[1]),o=i(t[2]);null===r||null===o||r in s||(s[r]=o)}return s}},7245:e=>{"use strict";e.exports=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}},1920:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupThebeLite=t.startJupyterLiteServer=void 0;const i=n(5163),s=n(315);function r(){var e;window.thebeLite=Object.assign(null!==(e=window.thebeLite)&&void 0!==e?e:{},{startJupyterLiteServer:s.startJupyterLiteServer})}Object.defineProperty(t,"startJupyterLiteServer",{enumerable:!0,get:function(){return s.startJupyterLiteServer}}),t.setupThebeLite=r,"undefined"!=typeof window&&(console.debug("window is defined, setting up thebe-lite"),r(),console.debug("window.thebeLite",window.thebeLite)),i.__exportStar(n(3173),t)},315:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.startJupyterLiteServer=void 0;const i=n(5163),s=n(9622),r=n(3800),o=[Promise.resolve().then((()=>i.__importStar(n(9671))))];function*a(e){let t;t=Object.prototype.hasOwnProperty.call(e,"__esModule")?e.default:e;const n=Array.isArray(t)?t:[t];for(const e of n)yield e}t.startJupyterLiteServer=function(e){return i.__awaiter(this,void 0,void 0,(function*(){s.PageConfig.getOption(""),(null==e?void 0:e.litePluginSettings)&&s.PageConfig.setOption("litePluginSettings",JSON.stringify(e.litePluginSettings));const t=[];(yield Promise.all(o)).forEach((e=>{for(const n of a(e))t.push(n)}));const l=[Promise.resolve().then((()=>i.__importStar(n(4957))))];[].forEach((e=>{e.liteExtension&&l.push(function(e,t){return i.__awaiter(this,void 0,void 0,(function*(){try{return(yield window._JUPYTERLAB[e].get(t))()}catch(n){throw console.warn(`Failed to create module: package: ${e}; module: ${t}`),n}}))}(e.name,e.extension))})),(yield Promise.allSettled(l)).forEach((e=>{if("fulfilled"===e.status)for(const n of a(e.value))t.push(n);else console.error(e.reason)}));const c=new r.JupyterLiteServer({});c.registerPluginModules(t),yield c.start();const{serviceManager:u}=c;return yield u.ready,u}))}},3173:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5163:(e,t,n)=>{"use strict";n.r(t),n.d(t,{__assign:()=>r,__asyncDelegator:()=>w,__asyncGenerator:()=>b,__asyncValues:()=>D,__await:()=>y,__awaiter:()=>u,__classPrivateFieldGet:()=>A,__classPrivateFieldSet:()=>k,__createBinding:()=>h,__decorate:()=>a,__exportStar:()=>p,__extends:()=>s,__generator:()=>d,__importDefault:()=>S,__importStar:()=>E,__makeTemplateObject:()=>x,__metadata:()=>c,__param:()=>l,__read:()=>m,__rest:()=>o,__spread:()=>g,__spreadArray:()=>_,__spreadArrays:()=>v,__values:()=>f});var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)};function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var r=function(){return r=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(s=e[a])&&(o=(r<3?s(o):r>3?s(t,n,o):s(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o}function l(e,t){return function(n,i){t(n,i,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function u(e,t,n,i){return new(n||(n=Promise))((function(s,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((i=i.apply(e,t||[])).next())}))}function d(e,t){var n,i,s,r,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,i&&(s=2&r[0]?i.return:r[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,r[1])).done)return s;switch(i=0,s&&(r=[2&r[0],s.value]),r[0]){case 0:case 1:s=r;break;case 4:return o.label++,{value:r[1],done:!1};case 5:o.label++,i=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,s,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function g(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(n=s[e](t)).value instanceof y?Promise.resolve(n.value.v).then(l,c):u(r[0][2],n)}catch(e){u(r[0][3],e)}var n}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),r.shift(),r.length&&a(r[0][0],r[0][1])}}function w(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,s){t[i]=e[i]?function(t){return(n=!n)?{value:y(e[i](t)),done:"return"===i}:s?s(t):t}:s}}function D(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=f(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,s){!function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)}(i,s,(t=e[n](t)).done,t.value)}))}}}function x(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var C=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&h(t,e,n);return C(t,e),t}function S(e){return e&&e.__esModule?e:{default:e}}function A(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function k(e,t,n,i,s){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?s.call(e,n):s?s.value=n:t.set(e,n),n}},4846:(e,t,n)=>{"use strict";var i=n(7245),s=n(7375),r=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,o=/[\n\r\t]/g,a=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,l=/:\d+$/,c=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,u=/^[a-zA-Z]:/;function d(e){return(e||"").toString().replace(r,"")}var h=[["#","hash"],["?","query"],function(e,t){return m(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],p={hash:1,query:1};function f(e){var t,i=("undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{}).location||{},s={},r=typeof(e=e||i);if("blob:"===e.protocol)s=new v(unescape(e.pathname),{});else if("string"===r)for(t in s=new v(e,{}),p)delete s[t];else if("object"===r){for(t in e)t in p||(s[t]=e[t]);void 0===s.slashes&&(s.slashes=a.test(e.href))}return s}function m(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function g(e,t){e=(e=d(e)).replace(o,""),t=t||{};var n,i=c.exec(e),s=i[1]?i[1].toLowerCase():"",r=!!i[2],a=!!i[3],l=0;return r?a?(n=i[2]+i[3]+i[4],l=i[2].length+i[3].length):(n=i[2]+i[4],l=i[2].length):a?(n=i[3]+i[4],l=i[3].length):n=i[4],"file:"===s?l>=2&&(n=n.slice(2)):m(s)?n=i[4]:s?r&&(n=n.slice(2)):l>=2&&m(t.protocol)&&(n=i[4]),{protocol:s,slashes:r||m(s),slashesCount:l,rest:n}}function v(e,t,n){if(e=(e=d(e)).replace(o,""),!(this instanceof v))return new v(e,t,n);var r,a,l,c,p,_,y=h.slice(),b=typeof t,w=this,D=0;for("object"!==b&&"string"!==b&&(n=t,t=null),n&&"function"!=typeof n&&(n=s.parse),r=!(a=g(e||"",t=f(t))).protocol&&!a.slashes,w.slashes=a.slashes||r&&t.slashes,w.protocol=a.protocol||t.protocol||"",e=a.rest,("file:"===a.protocol&&(2!==a.slashesCount||u.test(e))||!a.slashes&&(a.protocol||a.slashesCount<2||!m(w.protocol)))&&(y[3]=[/(.*)/,"pathname"]);D{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityMonitor=void 0;const i=n(4016);t.ActivityMonitor=class{constructor(e){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new i.Signal(this),e.signal.connect(this._onSignalFired,this),this._timeout=e.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(e){this._timeout=e}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,i.Signal.clearData(this))}_onSignalFired(e,t){clearTimeout(this._timer),this._sender=e,this._args=t,this._timer=setTimeout((()=>{this._activityStopped.emit({sender:this._sender,args:this._args})}),this._timeout)}}},9622:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(7542),t),s(n(2086),t),s(n(7390),t),s(n(9458),t),s(n(176),t),s(n(2643),t),s(n(7846),t),s(n(2533),t),s(n(7319),t)},2086:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},7390:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MarkdownCodeBlocks=void 0,function(e){e.CODE_BLOCK_MARKER="```";const t=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class n{constructor(e){this.startLine=e,this.code="",this.endLine=-1}}e.MarkdownCodeBlock=n,e.isMarkdown=function(e){return t.indexOf(e)>-1},e.findMarkdownCodeBlocks=function(t){if(!t||""===t)return[];const i=t.split("\n"),s=[];let r=null;for(let t=0;te===t||i&&e===i))},e.isDisabled=function(t){const n=t.indexOf(":");let i="";return-1!==n&&(i=t.slice(0,n)),e.disabled.some((e=>e===t||i&&e===i))}}(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))},176:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PathExt=void 0;const i=n(1023);!function(e){function t(e){return 0===e.indexOf("/")&&(e=e.slice(1)),e}e.join=function(...e){const n=i.posix.join(...e);return"."===n?"":t(n)},e.basename=function(e,t){return i.posix.basename(e,t)},e.dirname=function(e){const n=t(i.posix.dirname(e));return"."===n?"":n},e.extname=function(e){return i.posix.extname(e)},e.normalize=function(e){return""===e?"":t(i.posix.normalize(e))},e.resolve=function(...e){return t(i.posix.resolve(...e))},e.relative=function(e,n){return t(i.posix.relative(e,n))},e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e},e.removeSlash=t}(t.PathExt||(t.PathExt={}))},2643:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalToPromise=void 0;const i=n(5082);t.signalToPromise=function(e,t){const n=new i.PromiseDelegate;function s(){e.disconnect(r)}function r(e,t){s(),n.resolve([e,t])}return e.connect(r),(null!=t?t:0)>0&&setTimeout((()=>{s(),n.reject(`Signal not emitted within ${t} ms.`)}),t),n.promise}},7846:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Text=void 0,function(e){const t="𝐚".length>1;e.jsIndexToCharIndex=function(e,n){if(t)return e;let i=e;for(let t=0;t+1=55296&&e<=56319){const e=n.charCodeAt(t+1);e>=56320&&e<=57343&&(i--,t++)}}return i},e.charIndexToJsIndex=function(e,n){if(t)return e;let i=e;for(let e=0;e+1=55296&&t<=56319){const t=n.charCodeAt(e+1);t>=56320&&t<=57343&&(i++,e++)}}return i},e.camelCase=function(e,t=!1){return e.replace(/^(\w)|[\s-_:]+(\w)/g,(function(e,n,i){return i?i.toUpperCase():t?n.toUpperCase():n.toLowerCase()}))},e.titleCase=function(e){return(e||"").toLowerCase().split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(" ")}}(t.Text||(t.Text={}))},2533:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Time=void 0;const n=[{name:"years",milliseconds:31536e6},{name:"months",milliseconds:2592e6},{name:"days",milliseconds:864e5},{name:"hours",milliseconds:36e5},{name:"minutes",milliseconds:6e4},{name:"seconds",milliseconds:1e3}];var i;(i=t.Time||(t.Time={})).formatHuman=function(e){const t=document.documentElement.lang||"en",i=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),s=new Date(e).getTime()-Date.now();for(let e of n){const t=Math.ceil(s/e.milliseconds);if(0!==t)return i.format(t,e.name)}return i.format(0,"seconds")},i.format=function(e){const t=document.documentElement.lang||"en";return new Intl.DateTimeFormat(t,{dateStyle:"short",timeStyle:"short"}).format(new Date(e))}},7319:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.URLExt=void 0;const s=n(1023),r=i(n(4846));!function(e){function t(e){if("undefined"!=typeof document&&document){const t=document.createElement("a");return t.href=e,t}return(0,r.default)(e)}function n(...e){let t=(0,r.default)(e[0],{});const n=""===t.protocol&&t.slashes;n&&(t=(0,r.default)(e[0],"https:"+e[0]));const i=`${n?"":t.protocol}${t.slashes?"//":""}${t.auth}${t.auth?"@":""}${t.host}`,o=s.posix.join(`${i&&"/"!==t.pathname[0]?"/":""}${t.pathname}`,...e.slice(1));return`${i}${"."===o?"":o}`}e.parse=t,e.getHostName=function(e){return(0,r.default)(e).hostname},e.normalize=function(e){return e&&t(e).toString()},e.join=n,e.encodeParts=function(e){return n(...e.split("/").map(encodeURIComponent))},e.objectToQueryString=function(e){const t=Object.keys(e).filter((e=>e.length>0));return t.length?"?"+t.map((t=>{const n=encodeURIComponent(String(e[t]));return t+(n?"="+n:"")})).join("&"):""},e.queryStringToObject=function(e){return e.replace(/^\?/,"").split("&").reduce(((e,t)=>{const[n,i]=t.split("=");return n.length>0&&(e[n]=decodeURIComponent(i||"")),e}),{})},e.isLocal=function(e){const{protocol:n}=t(e);return(!n||0!==e.toLowerCase().indexOf(n))&&0!==e.indexOf("/")}}(t.URLExt||(t.URLExt={}))},5182:(e,t,n)=>{"use strict";n.d(t,{HB:()=>c,Hv:()=>a,dC:()=>u,vJ:()=>l});var i=n(9622),s=n(3893),r=n.n(s),o=n(5082);const a=new o.Token("@jupyterlite/contents:IContents");var l,c;!function(e){e.JSON="application/json",e.PLAIN_TEXT="text/plain",e.OCTET_STREAM="octet/stream"}(l||(l={})),function(e){const t=JSON.parse(i.PageConfig.getOption("fileTypes")||"{}");e.getType=function(e,n=null){e=e.toLowerCase();for(const n of Object.values(t))for(const t of n.extensions||[])if(t===e&&n.mimeTypes&&n.mimeTypes.length)return n.mimeTypes[0];return r().getType(e)||n||l.OCTET_STREAM},e.hasFormat=function(e,n){e=e.toLowerCase();for(const i of Object.values(t))if(i.fileFormat===n)for(const t of i.extensions||[])if(t===e)return!0;return!1}}(c||(c={}));const u=new o.Token("@jupyterlite/contents:IBroadcastChannelWrapper")},9842:(e,t,n)=>{"use strict";n.d(t,{Ll:()=>s,qP:()=>o,vM:()=>r});var i=n(5082);const s=new i.Token("@jupyterlite/kernel:IKernels"),r="javascript",o=new i.Token("@jupyterlite/kernel:IKernelSpecs")},4957:(e,t,n)=>{"use strict";n.r(t),n.d(t,{KERNEL_SETTINGS_SCHEMA:()=>l,default:()=>h});var i=n(9622),s=n(1729),r=n(9842),o=n(5182);const a=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema","$id":"https://jupyterlite-pyodide-kernel.readthedocs.org/en/latest/reference/schema/settings-v0.html#","title":"Pyodide Kernel Settings Schema v0","description":"Pyodide-specific configuration values. Will be defined in another location in the future.","type":"object","properties":{"pyodideUrl":{"description":"The path to the main pyodide.js entry point","type":"string","default":"https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js","format":"uri"},"disablePyPIFallback":{"description":"Disable the piplite behavior of falling back to https://pypi.org/pypi/","default":false,"type":"boolean"},"pipliteUrls":{"description":"Paths to PyPI-compatible API endpoints for wheels. If ending in ``all.json``, assumed to be an aggregate, keyed by package name, with relative paths","type":"array","items":{"type":"string"},"default":[],"format":"uri"}}}');var l=n.t(a,2),c=n(1173);const u=`data:image/svg+xml;base64,${btoa(n.n(c)())}`,d="@jupyterlite/pyodide-kernel-extension:kernel",h=[{id:d,autoStart:!0,requires:[r.qP],optional:[s.f,o.dC],activate:(e,t,s,r)=>{const o=JSON.parse(i.PageConfig.getOption("litePluginSettings")||"{}")[d]||{},a=o.pyodideUrl||"https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js",l=i.URLExt.parse(a).href,c=o.pipliteWheelUrl?i.URLExt.parse(o.pipliteWheelUrl).href:void 0,h=(o.pipliteUrls||[]).map((e=>i.URLExt.parse(e).href)),p=!!o.disablePyPIFallback;t.register({spec:{name:"python",display_name:"Python (Pyodide)",language:"python",argv:[],resources:{"logo-32x32":u,"logo-64x64":u}},create:async e=>{const{PyodideKernel:t}=await Promise.all([n.e(296),n.e(510)]).then(n.bind(n,144)),i=!(!(null==s?void 0:s.enabled)||!(null==r?void 0:r.enabled));return i?console.info("Pyodide contents will be synced with Jupyter Contents"):console.warn("Pyodide contents will NOT be synced with Jupyter Contents"),new t({...e,pyodideUrl:l,pipliteWheelUrl:c,pipliteUrls:h,disablePyPIFallback:p,mountDrive:i})}})}}]},9671:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>Q});var i=n(9622),s=n(5182),r=n(5082);const o="JupyterLite Storage";class a{constructor(e){this.reduceBytesToString=(e,t)=>e+String.fromCharCode(t),this._serverContents=new Map,this._storageName=o,this._storageDrivers=null,this._localforage=e.localforage,this._storageName=e.storageName||o,this._storageDrivers=e.storageDrivers||null,this._ready=new r.PromiseDelegate}async initialize(){await this.initStorage(),this._ready.resolve(void 0)}async initStorage(){this._storage=this.createDefaultStorage(),this._counters=this.createDefaultCounters(),this._checkpoints=this.createDefaultCheckpoints()}get ready(){return this._ready.promise}get storage(){return this.ready.then((()=>this._storage))}get counters(){return this.ready.then((()=>this._counters))}get checkpoints(){return this.ready.then((()=>this._checkpoints))}get defaultStorageOptions(){const e=this._storageDrivers&&this._storageDrivers.length?this._storageDrivers:null;return{version:1,name:this._storageName,...e?{driver:e}:{}}}createDefaultStorage(){return this._localforage.createInstance({description:"Offline Storage for Notebooks and Files",storeName:"files",...this.defaultStorageOptions})}createDefaultCounters(){return this._localforage.createInstance({description:"Store the current file suffix counters",storeName:"counters",...this.defaultStorageOptions})}createDefaultCheckpoints(){return this._localforage.createInstance({description:"Offline Storage for Checkpoints",storeName:"checkpoints",...this.defaultStorageOptions})}async newUntitled(e){var t,n,r;const o=null!==(t=null==e?void 0:e.path)&&void 0!==t?t:"",a=null!==(n=null==e?void 0:e.type)&&void 0!==n?n:"notebook",c=(new Date).toISOString();let u=i.PathExt.dirname(o);const d=i.PathExt.basename(o),h=i.PathExt.extname(o),p=await this.get(u);let f,m="";switch(o&&!h&&p?(u=`${o}/`,m=""):u&&d?(u=`${u}/`,m=d):(u="",m=o),a){case"directory":m=`Untitled Folder${await this._incrementCounter("directory")||""}`,f={name:m,path:`${u}${m}`,last_modified:c,created:c,format:"json",mimetype:"",content:null,size:0,writable:!0,type:"directory"};break;case"notebook":{const e=await this._incrementCounter("notebook");m=m||`Untitled${e||""}.ipynb`,f={name:m,path:`${u}${m}`,last_modified:c,created:c,format:"json",mimetype:s.vJ.JSON,content:l.EMPTY_NB,size:JSON.stringify(l.EMPTY_NB).length,writable:!0,type:"notebook"};break}default:{const t=null!==(r=null==e?void 0:e.ext)&&void 0!==r?r:".txt",n=await this._incrementCounter("file"),i=s.HB.getType(t)||s.vJ.OCTET_STREAM;let o;o=s.HB.hasFormat(t,"text")||-1!==i.indexOf("text")?"text":-1!==t.indexOf("json")||-1!==t.indexOf("ipynb")?"json":"base64",m=m||`untitled${n||""}${t}`,f={name:m,path:`${u}${m}`,last_modified:c,created:c,format:o,mimetype:i,content:"",size:0,writable:!0,type:"file"};break}}const g=f.path;return await(await this.storage).setItem(g,f),f}async copy(e,t){let n=i.PathExt.basename(e);for(t=""===t?"":`${t.slice(1)}/`;await this.get(`${t}${n}`,{content:!0});){const e=i.PathExt.extname(n),t=n.replace(e,"");n=`${t} (copy)${e}`}const s=`${t}${n}`;let r=await this.get(e,{content:!0});if(!r)throw Error(`Could not find file with path ${e}`);return r={...r,name:n,path:s},await(await this.storage).setItem(s,r),r}async get(e,t){if(""===(e=decodeURIComponent(e.replace(/^\//,""))))return await this._getFolder(e);const n=await this.storage,r=await n.getItem(e),o=await this._getServerContents(e,t),a=r||o;if(!a)return null;if(!(null==t?void 0:t.content))return{size:0,...a,content:null};if("directory"===a.type){const t=new Map;await n.iterate(((n,i)=>{i===`${e}/${n.name}`&&t.set(n.name,n)}));const r=o?o.content:Array.from((await this._getServerDirectory(e)).values());for(const e of r)t.has(e.name)||t.set(e.name,e);const l=[...t.values()];return{name:i.PathExt.basename(e),path:e,last_modified:a.last_modified,created:a.created,format:"json",mimetype:s.vJ.JSON,content:l,size:0,writable:!0,type:"directory"}}return a}async rename(e,t){const n=decodeURIComponent(e),s=await this.get(n,{content:!0});if(!s)throw Error(`Could not find file with path ${n}`);const r=(new Date).toISOString(),o=i.PathExt.basename(t),a={...s,name:o,path:t,last_modified:r},l=await this.storage;if(await l.setItem(t,a),await l.removeItem(n),await(await this.checkpoints).removeItem(n),"directory"===s.type){let n;for(n of s.content)await this.rename(i.URLExt.join(e,n.name),i.URLExt.join(t,n.name))}return a}async save(e,t={}){var n;e=decodeURIComponent(e);const r=i.PathExt.extname(null!==(n=t.name)&&void 0!==n?n:""),o=t.chunk,a=!!o&&(o>1||-1===o);let l=await this.get(e,{content:a});if(l||(l=await this.newUntitled({path:e,ext:r,type:"file"})),!l)return null;const c=l.content,u=(new Date).toISOString();if(l={...l,...t,last_modified:u},t.content&&"base64"===t.format){const e=!o||-1===o;if(".ipynb"===r){const n=this._handleChunk(t.content,c,a);l={...l,content:e?JSON.parse(n):n,format:"json",type:"notebook",size:n.length}}else if(s.HB.hasFormat(r,"json")){const n=this._handleChunk(t.content,c,a);l={...l,content:e?JSON.parse(n):n,format:"json",type:"file",size:n.length}}else if(s.HB.hasFormat(r,"text")){const e=this._handleChunk(t.content,c,a);l={...l,content:e,format:"text",type:"file",size:e.length}}else{const e=t.content;l={...l,content:e,size:atob(e).length}}}return await(await this.storage).setItem(e,l),l}async delete(e){const t=`${e=decodeURIComponent(e)}/`,n=(await(await this.storage).keys()).filter((n=>n===e||n.startsWith(t)));await Promise.all(n.map(this.forgetPath,this))}async forgetPath(e){await Promise.all([(await this.storage).removeItem(e),(await this.checkpoints).removeItem(e)])}async createCheckpoint(e){var t;const n=await this.checkpoints;e=decodeURIComponent(e);const i=await this.get(e,{content:!0});if(!i)throw Error(`Could not find file with path ${e}`);const s=(null!==(t=await n.getItem(e))&&void 0!==t?t:[]).filter(Boolean);return s.push(i),s.length>5&&s.splice(0,s.length-5),await n.setItem(e,s),{id:""+(s.length-1),last_modified:i.last_modified}}async listCheckpoints(e){return(await(await this.checkpoints).getItem(e)||[]).filter(Boolean).map(this.normalizeCheckpoint,this)}normalizeCheckpoint(e,t){return{id:t.toString(),last_modified:e.last_modified}}async restoreCheckpoint(e,t){e=decodeURIComponent(e);const n=(await(await this.checkpoints).getItem(e)||[])[parseInt(t)];await(await this.storage).setItem(e,n)}async deleteCheckpoint(e,t){e=decodeURIComponent(e);const n=await(await this.checkpoints).getItem(e)||[],i=parseInt(t);n.splice(i,1),await(await this.checkpoints).setItem(e,n)}_handleChunk(e,t,n){const i=decodeURIComponent(escape(atob(e)));return n?t+i:i}async _getFolder(e){const t=new Map,n=await this.storage;await n.iterate(((e,n)=>{n.includes("/")||t.set(e.path,e)}));for(const n of(await this._getServerDirectory(e)).values())t.has(n.path)||t.set(n.path,n);return e&&0===t.size?null:{name:"",path:e,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:"json",mimetype:s.vJ.JSON,content:Array.from(t.values()),size:0,writable:!0,type:"directory"}}async _getServerContents(e,t){const n=i.PathExt.basename(e);let r=(await this._getServerDirectory(i.URLExt.join(e,".."))).get(n);if(!r)return null;if(r=r||{name:n,path:e,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:"text",mimetype:s.vJ.PLAIN_TEXT,type:"file",writable:!0,size:0,content:""},null==t?void 0:t.content)if("directory"===r.type){const t=await this._getServerDirectory(e);r={...r,content:Array.from(t.values())}}else{const t=i.URLExt.join(i.PageConfig.getBaseUrl(),"files",e),o=await fetch(t);if(!o.ok)return null;const a=r.mimetype||o.headers.get("Content-Type"),l=i.PathExt.extname(n);if("notebook"===r.type||s.HB.hasFormat(l,"json")||-1!==(null==a?void 0:a.indexOf("json"))||e.match(/\.(ipynb|[^/]*json[^/]*)$/)){const e=await o.text();r={...r,content:JSON.parse(e),format:"json",mimetype:r.mimetype||s.vJ.JSON,size:e.length}}else if(s.HB.hasFormat(l,"text")||-1!==a.indexOf("text")){const e=await o.text();r={...r,content:e,format:"text",mimetype:a||s.vJ.PLAIN_TEXT,size:e.length}}else{const e=await o.arrayBuffer(),t=new Uint8Array(e);r={...r,content:btoa(t.reduce(this.reduceBytesToString,"")),format:"base64",mimetype:a||s.vJ.OCTET_STREAM,size:t.length}}}return r}async _getServerDirectory(e){const t=this._serverContents.get(e)||new Map;if(!this._serverContents.has(e)){const n=i.URLExt.join(i.PageConfig.getBaseUrl(),"api/contents",e,"all.json");try{const e=await fetch(n),i=JSON.parse(await e.text());for(const e of i.content)t.set(e.name,e)}catch(e){console.warn(`don't worry, about ${e}... nothing's broken. If there had been a\n file at ${n}, you might see some more files.`)}this._serverContents.set(e,t)}return t}async _incrementCounter(e){var t;const n=await this.counters,i=(null!==(t=await n.getItem(e))&&void 0!==t?t:-1)+1;return await n.setItem(e,i),i}}var l;!function(e){e.EMPTY_NB={metadata:{orig_nbformat:4},nbformat_minor:4,nbformat:4,cells:[]}}(l||(l={}));const c=16895;new TextEncoder,new TextDecoder("utf-8");class u{constructor(e){this.isDisposed=!1,this._onMessage=async e=>{if(!this._channel)return;const{_contents:t}=this,n=e.data,s=null==n?void 0:n.path;if("broadcast.ts"!==(null==n?void 0:n.receiver))return;let r,o=null;switch(null==n?void 0:n.method){case"readdir":r=await t.get(s,{content:!0}),o=[],"directory"===r.type&&r.content&&(o=r.content.map((e=>e.name)));break;case"rmdir":await t.delete(s);break;case"rename":await t.rename(s,n.data.newPath);break;case"getmode":r=await t.get(s),o="directory"===r.type?c:33206;break;case"lookup":try{r=await t.get(s),o={ok:!0,mode:"directory"===r.type?c:33206}}catch(e){o={ok:!1}}break;case"mknod":r=await t.newUntitled({path:i.PathExt.dirname(s),type:Number.parseInt(n.data.mode)===c?"directory":"file",ext:i.PathExt.extname(s)}),await t.rename(r.path,s);break;case"getattr":{r=await t.get(s);const e=new Date(0).toISOString();o={dev:1,nlink:1,uid:0,gid:0,rdev:0,size:r.size||0,blksize:4096,blocks:Math.ceil(r.size||0),atime:r.last_modified||e,mtime:r.last_modified||e,ctime:r.created||e,timestamp:0};break}case"get":if(r=await t.get(s,{content:!0}),"directory"===r.type)break;o={content:"json"===r.format?JSON.stringify(r.content):r.content,format:r.format};break;case"put":await t.save(s,{content:"json"===n.data.format?JSON.parse(n.data.data):n.data.data,type:"file",format:n.data.format});break;default:o=null}this._channel.postMessage(o)},this._channel=null,this._enabled=!1,this._contents=e.contents}get enabled(){return this._enabled}enable(){this._channel?console.warn("BroadcastChannel already created and enabled"):(this._channel=new BroadcastChannel("/api/drive.v1"),this._channel.addEventListener("message",this._onMessage),this._enabled=!0)}disable(){this._channel&&(this._channel.removeEventListener("message",this._onMessage),this._channel=null),this._enabled=!1}dispose(){this.isDisposed||(this.disable(),this.isDisposed=!0)}}var d,h=n(9842),p=n(4016);class f{constructor(e={}){if(this._map=new Map,this._changed=new p.Signal(this),this._isDisposed=!1,this._itemCmp=e.itemCmp||d.itemCmp,e.values)for(const t in e.values)this._map.set(t,e.values[t])}get type(){return"Map"}get changed(){return this._changed}get isDisposed(){return this._isDisposed}get size(){return this._map.size}set(e,t){const n=this._map.get(e);if(void 0===t)throw Error("Cannot set an undefined value, use remove");const i=this._itemCmp;return void 0!==n&&i(n,t)||(this._map.set(e,t),this._changed.emit({type:n?"change":"add",key:e,oldValue:n,newValue:t})),n}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){const e=[];return this._map.forEach(((t,n)=>{e.push(n)})),e}values(){const e=[];return this._map.forEach(((t,n)=>{e.push(t)})),e}delete(e){const t=this._map.get(e);return this._map.delete(e)&&this._changed.emit({type:"remove",key:e,oldValue:t,newValue:void 0}),t}clear(){const e=this.keys();for(let t=0;tthis._queue.push({resolve:e,reject:t})));return e||this._dispatch(),t}runExclusive(e){return y(this,void 0,void 0,(function*(){const[t,n]=yield this.acquire();try{return yield e(t)}finally{n()}}))}waitForUnlock(){return y(this,void 0,void 0,(function*(){return this.isLocked()?new Promise((e=>this._waiters.push({resolve:e}))):Promise.resolve()}))}isLocked(){return this._value<=0}release(){if(this._maxConcurrency>1)throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead");if(this._currentReleaser){const e=this._currentReleaser;this._currentReleaser=void 0,e()}}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatch(){const e=this._queue.shift();if(!e)return;let t=!1;this._currentReleaser=()=>{t||(t=!0,this._value++,this._resolveWaiters(),this._dispatch())},e.resolve([this._value--,this._currentReleaser])}_resolveWaiters(){this._waiters.forEach((e=>e.resolve())),this._waiters=[]}}class w{constructor(e){this._semaphore=new b(1,e)}acquire(){return e=this,t=void 0,i=function*(){const[,e]=yield this._semaphore.acquire();return e},new((n=void 0)||(n=Promise))((function(s,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((i=i.apply(e,t||[])).next())}));var e,t,n,i}runExclusive(e){return this._semaphore.runExclusive((()=>e()))}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const D=g.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg;class x{constructor(e){this._kernels=new f,this._clients=new f,this._kernelClients=new f;const{kernelspecs:t}=e;this._kernelspecs=t}async startNew(e){const{id:t,name:n,location:i}=e,s=this._kernelspecs.factories.get(n);if(!s)return{id:t,name:n};const o=new w,a=(e,t,n)=>{var i;const s=this._kernels.get(e);if(!s)throw Error(`No kernel ${e}`);this._clients.set(t,n),null===(i=this._kernelClients.get(e))||void 0===i||i.add(t),n.on("message",(async e=>{let t;if(e instanceof ArrayBuffer)e=new Uint8Array(e).buffer,t=(0,m.deserialize)(e,D);else{if("string"!=typeof e)return;{const n=(new TextEncoder).encode(e);t=(0,m.deserialize)(n.buffer,D)}}"input_reply"===t.header.msg_type?s.handleMessage(t):(async e=>{await o.runExclusive((async()=>{await s.ready,await s.handleMessage(e)}))})(t)}));const r=()=>{var n;this._clients.delete(t),null===(n=this._kernelClients.get(e))||void 0===n||n.delete(t)};s.disposed.connect(r),n.onclose=r},l=null!=t?t:r.UUID.uuid4(),c=`${x.WS_BASE_URL}api/kernels/${l}/channels`,u=this._kernels.get(l);if(u)return{id:u.id,name:u.name};const d=await s({id:l,sendMessage:e=>{const t=e.header.session,n=this._clients.get(t);if(!n)return void console.warn(`Trying to send message on removed socket for kernel ${l}`);const i=(0,m.serialize)(e,D);if("iopub"!==e.channel)n.send(i);else{const e=this._kernelClients.get(l);null==e||e.forEach((e=>{var t;null===(t=this._clients.get(e))||void 0===t||t.send(i)}))}},name:n,location:i});this._kernels.set(l,d),this._kernelClients.set(l,new Set);const h=new v.Server(c,{mock:!1,selectProtocol:()=>D});return h.on("connection",(e=>{var t;const n=null!==(t=new URL(e.url).searchParams.get("session_id"))&&void 0!==t?t:"";a(l,n,e)})),h.on("close",(()=>{this._clients.keys().forEach((e=>{var t;const n=this._clients.get(e);(null==n?void 0:n.readyState)===WebSocket.CLOSED&&(this._clients.delete(e),null===(t=this._kernelClients.get(l))||void 0===t||t.delete(e))}))})),d.disposed.connect((()=>{h.close(),this._kernels.delete(l),this._kernelClients.delete(l)})),{id:d.id,name:d.name}}async restart(e){const t=this._kernels.get(e);if(!t)throw Error(`Kernel ${e} does not exist`);const{id:n,name:i,location:s}=t;return t.dispose(),this.startNew({id:n,name:i,location:s})}async list(){return[...this._kernels.values()].map((e=>({id:e.id,name:e.name})))}async shutdown(e){var t;null===(t=this._kernels.delete(e))||void 0===t||t.dispose()}async get(e){return this._kernels.get(e)}}!function(e){e.WS_BASE_URL=i.PageConfig.getBaseUrl().replace(/^http/,"ws")}(x||(x={}));class C{constructor(){this._specs=new Map,this._factories=new Map}get specs(){return 0===this._specs.size?null:{default:this.defaultKernelName,kernelspecs:Object.fromEntries(this._specs)}}get defaultKernelName(){let e=i.PageConfig.getOption("defaultKernelName");if(!e&&this._specs.size){const t=Array.from(this._specs.keys());t.sort(),e=t[0]}return e||h.vM}get factories(){return this._factories}register(e){const{spec:t,create:n}=e;this._specs.set(t.name,t),this._factories.set(t.name,n)}}const E="third-party-licenses.json",S=new r.Token("@jupyterlite/licenses:ILicenses"),A=Object.freeze({packages:[]});class k{async get(){return{bundles:{...await this._getFederated(),[this.appName]:await this._getAppLicenses()}}}get appName(){return i.PageConfig.getOption("appName")||"JupyterLite"}get appLicensesUrl(){return i.URLExt.join(i.PageConfig.getBaseUrl(),"build",E)}get labExtensionsUrl(){return i.PageConfig.getOption("fullLabextensionsUrl")}async _getAppLicenses(){let e=A;try{e=(await fetch(this.appLicensesUrl)).json()}catch(e){console.warn("Could not resolve licenses for",this.appName)}return e}async _getFederated(){const e={};let t;try{t=JSON.parse(i.PageConfig.getOption("federated_extensions"))}catch{return e}const n=[];for(const i of t)n.push(this._getOneFederated(i,e));try{await Promise.all(n)}catch(e){console.warn("Error resolving licenses",e)}return e}async _getOneFederated(e,t){try{const n=i.URLExt.join(this.labExtensionsUrl,e.name,"static",E),s=await fetch(n);t[e.name]=await s.json()}catch{console.warn("Could not resolve licenses for",e),t[e.name]=A}}}var M=n(1729),F=n(3570);const I=new r.Token("@jupyterlite/session:ISessions");var O=n(5259);class P{constructor(e){this._sessions=[],this._kernels=e.kernels}async get(e){const t=this._sessions.find((t=>t.id===e));if(!t)throw Error(`Session ${e} not found`);return t}async list(){return this._sessions}async patch(e){const{id:t,path:n,name:s,kernel:o}=e,a=this._sessions.findIndex((e=>e.id===t)),l=this._sessions[a];if(!l)throw Error(`Session ${t} not found`);const c={...l,path:null!=n?n:l.path,name:null!=s?s:l.name};if(o)if(o.id){const e=this._sessions.find((e=>{var t;return(null===(t=e.kernel)||void 0===t?void 0:t.id)===(null==o?void 0:o.id)}));e&&(c.kernel=e.kernel)}else if(o.name){const e=await this._kernels.startNew({id:r.UUID.uuid4(),name:o.name,location:i.PathExt.dirname(c.path)});e&&(c.kernel=e),this._handleKernelShutdown({kernelId:e.id,sessionId:l.id})}return this._sessions[a]=c,c}async startNew(e){var t,n,s,o;const{path:a,name:l}=e,c=this._sessions.find((e=>e.name===l));if(c)return c;const u=null!==(n=null===(t=e.kernel)||void 0===t?void 0:t.name)&&void 0!==n?n:"",d=null!==(s=e.id)&&void 0!==s?s:r.UUID.uuid4(),h=null!==(o=e.name)&&void 0!==o?o:e.path,p=i.PathExt.dirname(e.name)||i.PathExt.dirname(e.path),f=h.includes(":")?h.split(":")[0]:"",m=p.includes(f)?p:`${f}:${p}`,g=await this._kernels.startNew({id:d,name:u,location:m}),v={id:d,path:a,name:null!=l?l:a,type:"notebook",kernel:{id:g.id,name:g.name}};return this._sessions.push(v),this._handleKernelShutdown({kernelId:d,sessionId:v.id}),v}async shutdown(e){var t;const n=this._sessions.find((t=>t.id===e));if(!n)throw Error(`Session ${e} not found`);const i=null===(t=n.kernel)||void 0===t?void 0:t.id;i&&await this._kernels.shutdown(i),O.RO.removeFirstOf(this._sessions,n)}async _handleKernelShutdown({kernelId:e,sessionId:t}){const n=await this._kernels.get(e);n&&n.disposed.connect((()=>{this.shutdown(t)}))}}const B=new r.Token("@jupyterlite/settings:ISettings");var R=n(6111);const T="JupyterLite Storage";class L{constructor(e){this._storageName=T,this._storageDrivers=null,this._localforage=e.localforage,this._storageName=e.storageName||T,this._storageDrivers=e.storageDrivers||null,this._ready=new r.PromiseDelegate}get ready(){return this._ready.promise}get storage(){return this.ready.then((()=>this._storage))}async initialize(){await this.initStorage(),this._ready.resolve(void 0)}async initStorage(){this._storage=this.defaultSettingsStorage()}get defaultStorageOptions(){var e;const t=(null===(e=this._storageDrivers)||void 0===e?void 0:e.length)?this._storageDrivers:null;return{version:1,name:this._storageName,...t?{driver:t}:{}}}defaultSettingsStorage(){return this._localforage.createInstance({description:"Offline Storage for Settings",storeName:"settings",...this.defaultStorageOptions})}async get(e){return(await this.getAll()).settings.find((t=>t.id===e))}async getAll(){const[e,t]=await Promise.all([this._getAll("all.json"),this._getAll("all_federated.json")]),n=e.concat(t),i=await this.storage;return{settings:await Promise.all(n.map((async e=>{var t;const{id:n}=e,s=null!==(t=await i.getItem(n))&&void 0!==t?t:e.raw;return{...j.override(e),raw:s,settings:R.parse(s)}})))}}async save(e,t){await(await this.storage).setItem(e,t)}async _getAll(e){var t;const n=null!==(t=i.PageConfig.getOption("settingsUrl"))&&void 0!==t?t:"/";return await(await fetch(i.URLExt.join(n,e))).json()}}var j;!function(e){const t=JSON.parse(i.PageConfig.getOption("settingsOverrides")||"{}");e.override=function(e){if(t[e.id]){e.schema.properties||(e.schema.properties={});for(const[n,i]of Object.entries(t[e.id]||{}))e.schema.properties[n].default=i}return e}}(j||(j={}));const N=new r.Token("@jupyterlite/translation:ITranslation");class z{constructor(){this._prevLocale=""}async get(e){const t=i.URLExt.join(i.PageConfig.getBaseUrl(),`api/translations/${e}.json`);try{const n=await fetch(t),i=JSON.parse(await n.text());if("all"!==this._prevLocale&&"all"===e){const e=this._prevLocale;i.data[e].displayName=i.data[e].nativeName,"en"!==e&&(i.data.en.displayName=`${i.data.en.nativeName} (default)`)}return this._prevLocale=e,i}catch(t){return e?{data:{},message:`Language pack '${e}' not installed!`}:{data:{en:{displayName:"English",nativeName:"English"}},message:""}}}}const U=new r.Token("@jupyterlite/localforge:ILocalForage");var q=n(1976),W=n.n(q),H=n(5486),K=n.n(H);const $={id:"@jupyterlite/server-extension:localforage",autoStart:!0,provides:U,activate:e=>({localforage:K()})},V={id:"@jupyterlite/server-extension:localforage-memory-storage",autoStart:!0,requires:[U],activate:async(e,t)=>{JSON.parse(i.PageConfig.getOption("enableMemoryStorage")||"false")&&(console.warn("Memory storage fallback enabled: contents and settings may not be saved"),await async function(e){return await e.defineDriver(W())}(t.localforage))}},J={id:"@jupyterlite/server-extension:contents",requires:[U],autoStart:!0,provides:s.Hv,activate:(e,t)=>{const n=i.PageConfig.getOption("contentsStorageName"),s=JSON.parse(i.PageConfig.getOption("contentsStorageDrivers")||"null"),{localforage:r}=t,o=new a({storageName:n,storageDrivers:s,localforage:r});return e.started.then((()=>o.initialize().catch(console.warn))),o}},G={id:"@jupyterlite/server-extension:contents-routes",autoStart:!0,requires:[s.Hv],activate:(e,t)=>{e.router.get("/api/contents/(.+)/checkpoints",(async(e,n)=>{const i=await t.listCheckpoints(n);return new Response(JSON.stringify(i))})),e.router.post("/api/contents/(.+)/checkpoints/(.*)",(async(e,n,i)=>{const s=await t.restoreCheckpoint(n,i);return new Response(JSON.stringify(s),{status:204})})),e.router.post("/api/contents/(.+)/checkpoints",(async(e,n)=>{const i=await t.createCheckpoint(n);return new Response(JSON.stringify(i),{status:201})})),e.router.delete("/api/contents/(.+)/checkpoints/(.*)",(async(e,n,i)=>{const s=await t.deleteCheckpoint(n,i);return new Response(JSON.stringify(s),{status:204})})),e.router.get("/api/contents(.*)",(async(e,n)=>{var i;const s={content:"1"===(null===(i=e.query)||void 0===i?void 0:i.content)},r=await t.get(n,s);return r?new Response(JSON.stringify(r)):new Response(null,{status:404})})),e.router.post("/api/contents(.*)",(async(e,n)=>{const i=e.body,s=null==i?void 0:i.copy_from;let r;return r=s?await t.copy(s,n):await t.newUntitled(i),r?new Response(JSON.stringify(r),{status:201}):new Response(null,{status:400})})),e.router.patch("/api/contents(.*)",(async(e,n)=>{var i,s;const r=null!==(s=null===(i=e.body)||void 0===i?void 0:i.path)&&void 0!==s?s:"";n="/"===n[0]?n.slice(1):n;const o=await t.rename(n,r);return new Response(JSON.stringify(o))})),e.router.put("/api/contents/(.+)",(async(e,n)=>{const i=e.body,s=await t.save(n,i);return new Response(JSON.stringify(s))})),e.router.delete("/api/contents/(.+)",(async(e,n)=>(await t.delete(n),new Response(null,{status:204}))))}},Y={id:"@jupyterlite/server-extension:service-worker",autoStart:!0,provides:M.f,activate:e=>new F.Z},X={id:"@jupyterlite/server-extension:settings",autoStart:!0,requires:[U],provides:B,activate:(e,t)=>{const n=i.PageConfig.getOption("settingsStorageName"),s=JSON.parse(i.PageConfig.getOption("settingsStorageDrivers")||"null"),{localforage:r}=t,o=new L({storageName:n,storageDrivers:s,localforage:r});return e.started.then((()=>o.initialize().catch(console.warn))),o}},Z={id:"@jupyterlite/server-extension:settings-routes",autoStart:!0,requires:[B],activate:(e,t)=>{const n="/api/settings/((?:@([^/]+?)[/])?([^/]+?):([^:]+))$";e.router.get(n,(async(e,n)=>{const i=await t.get(n);return new Response(JSON.stringify(i))})),e.router.put(n,(async(e,n)=>{const i=e.body,{raw:s}=i;return await t.save(n,s),new Response(null,{status:204})})),e.router.get("/api/settings",(async e=>{const n=await t.getAll();return new Response(JSON.stringify(n))}))}},Q=[J,G,{id:"@jupyterlite/server-extension:emscripten-filesystem",autoStart:!0,optional:[M.f],provides:s.dC,activate:(e,t)=>{const{contents:n}=e.serviceManager,i=new u({contents:n}),s="Kernel filesystem and JupyterLite contents";function r(e,t){t&&console.warn(t),e&&console.warn(e),t||e?console.warn(`${s} will NOT be synced`):console.info(`${s} will be synced`)}return t?t.ready.then((()=>{i.enable(),r()})).catch((e=>{r("JupyterLite ServiceWorker failed to become available",e)})):r("JupyterLite ServiceWorker not available"),i}},{id:"@jupyterlite/server-extension:kernels",autoStart:!0,provides:h.Ll,requires:[h.qP],activate:(e,t)=>new x({kernelspecs:t})},{id:"@jupyterlite/server-extension:kernels-routes",autoStart:!0,requires:[h.Ll],activate:(e,t)=>{e.router.get("/api/kernels",(async e=>{const n=await t.list();return new Response(JSON.stringify(n))})),e.router.post("/api/kernels/(.*)/restart",(async(e,n)=>{const i=await t.restart(n);return new Response(JSON.stringify(i))})),e.router.delete("/api/kernels/(.*)",(async(e,n)=>{const i=await t.shutdown(n);return new Response(JSON.stringify(i),{status:204})}))}},{id:"@jupyterlite/server-extension:kernelspec",autoStart:!0,provides:h.qP,activate:e=>new C},{id:"@jupyterlite/server-extension:kernelspec-routes",autoStart:!0,requires:[h.qP],activate:(e,t)=>{e.router.get("/api/kernelspecs",(async e=>{const{specs:n}=t;if(!n)return new Response(null);const i={},s=n.kernelspecs;Object.keys(s).forEach((e=>{const t=s[e],{resources:n}=null!=t?t:{};i[e]={name:e,spec:t,resources:n}}));const r={default:n.default,kernelspecs:i};return new Response(JSON.stringify(r))}))}},{id:"@jupyterlite/server-extension:licenses",autoStart:!0,provides:S,activate:e=>new k},{id:"@jupyterlite/server-extension:licenses-routes",autoStart:!0,requires:[S],activate(e,t){e.router.get("/api/licenses",(async e=>{const n=await t.get();return new Response(JSON.stringify(n))}))}},V,$,{id:"@jupyterlite/server-extension:lsp-routes",autoStart:!0,activate:e=>{e.router.get("/lsp/status",(async e=>new Response(JSON.stringify({version:2,sessions:{},specs:{}}))))}},{id:"@jupyterlite/server-extension:nbconvert-routes",autoStart:!0,activate:e=>{e.router.get("/api/nbconvert",(async e=>new Response(JSON.stringify({}))))}},Y,{id:"@jupyterlite/server-extension:sessions",autoStart:!0,provides:I,requires:[h.Ll],activate:(e,t)=>new P({kernels:t})},{id:"@jupyterlite/server-extension:sessions-routes",autoStart:!0,requires:[I],activate:(e,t)=>{e.router.get("/api/sessions/(.+)",(async(e,n)=>{const i=await t.get(n);return new Response(JSON.stringify(i),{status:200})})),e.router.get("/api/sessions",(async e=>{const n=await t.list();return new Response(JSON.stringify(n),{status:200})})),e.router.patch("/api/sessions(.*)",(async(e,n)=>{const i=e.body,s=await t.patch(i);return new Response(JSON.stringify(s),{status:200})})),e.router.delete("/api/sessions/(.+)",(async(e,n)=>(await t.shutdown(n),new Response(null,{status:204})))),e.router.post("/api/sessions",(async e=>{const n=e.body,i=await t.startNew(n);return new Response(JSON.stringify(i),{status:201})}))}},X,Z,{id:"@jupyterlite/server-extension:translation",autoStart:!0,provides:N,activate:e=>{const t=new z;return e.router.get("/api/translations/?(.*)",(async(e,n)=>{"default"===n&&(n="en");const i=await t.get(n||"all");return new Response(JSON.stringify(i))})),t}},{id:"@jupyterlite/server-extension:translation-routes",autoStart:!0,requires:[N],activate:(e,t)=>{e.router.get("/api/translations/?(.*)",(async(e,n)=>{const i=await t.get(n||"all");return new Response(JSON.stringify(i))}))}}]},3800:(e,t,n)=>{"use strict";n.r(t),n.d(t,{IServiceWorkerManager:()=>ct.f,JupyterLiteServer:()=>lt,Router:()=>ot,ServiceWorkerManager:()=>ut.Z,WORKER_NAME:()=>ct.o});var i,s,r,o,a,l,c,u=n(6914),d=n(5259),h=n(5082),p=n(4016);class f{constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class m{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(m||(m={}));class g extends m{constructor(){super(...arguments),this._disposed=new p.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),p.Signal.clearData(this))}}function v(){return b.keyboardLayout}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(g||(g={})),function(e){e.copyText=function(e){const t=document.body,n=i=>{i.preventDefault(),i.stopPropagation(),i.clipboardData.setData("text",e),t.removeEventListener("copy",n,!0)};t.addEventListener("copy",n,!0),document.execCommand("copy")}}(i||(i={})),(c=s||(s={})).boxSizing=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,i=parseFloat(t.borderLeftWidth)||0,s=parseFloat(t.borderRightWidth)||0,r=parseFloat(t.borderBottomWidth)||0,o=parseFloat(t.paddingTop)||0,a=parseFloat(t.paddingLeft)||0,l=parseFloat(t.paddingRight)||0,c=parseFloat(t.paddingBottom)||0;return{borderTop:n,borderLeft:i,borderRight:s,borderBottom:r,paddingTop:o,paddingLeft:a,paddingRight:l,paddingBottom:c,horizontalSum:i+a+l+s,verticalSum:n+o+c+r}},c.sizeLimits=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.minWidth)||0,i=parseFloat(t.minHeight)||0,s=parseFloat(t.maxWidth)||1/0,r=parseFloat(t.maxHeight)||1/0;return s=Math.max(n,s),r=Math.max(i,r),{minWidth:n,minHeight:i,maxWidth:s,maxHeight:r}},c.hitTest=function(e,t,n){let i=e.getBoundingClientRect();return t>=i.left&&t=i.top&&n=n.bottom||(i.topn.bottom&&i.height>=n.height?e.scrollTop-=n.top-i.top:(i.topn.height||i.bottom>n.bottom&&i.height{let e=Element.prototype;return e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(e){let t=this,n=t.ownerDocument?t.ownerDocument.querySelectorAll(e):[];return-1!==Array.prototype.indexOf.call(n,t)}})(),e.calculateSingle=function(e){let c=0,u=0,d=0;function h(t){let n=e.match(t);return null!==n&&(e=e.slice(n[0].length),!0)}for(e=(e=e.split(",",1)[0]).replace(l," $1 ");e.length>0;)if(h(t))c++;else if(h(n))u++;else if(h(i))u++;else if(h(r))d++;else if(h(o))u++;else if(h(s))d++;else if(!h(a))return 0;return c=Math.min(c,255),u=Math.min(u,255),d=Math.min(d,255),c<<16|u<<8|d};const t=/^#[^\s\+>~#\.\[:]+/,n=/^\.[^\s\+>~#\.\[:]+/,i=/^\[[^\]]+\]/,s=/^[^\s\+>~#\.\[:]+/,r=/^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/,o=/^:[^\s\+>~#\.\[:]+/,a=/^[\s\+>~\*]+/,l=/:not\(([^\)]+)\)/g}(a||(a={}));class _{constructor(e,t,n=[]){this.name=e,this._codes=t,this._keys=_.extractKeys(t),this._modifierKeys=_.convertToKeySet(n)}keys(){return Object.keys(this._keys)}isValidKey(e){return e in this._keys}isModifierKey(e){return e in this._modifierKeys}keyForKeydownEvent(e){return this._codes[e.keyCode]||""}}!function(e){e.extractKeys=function(e){let t=Object.create(null);for(let n in e)t[e[n]]=!0;return t},e.convertToKeySet=function(e){let t=Object(null);for(let n=0,i=e.length;n{this._commands.delete(e),this._commandChanged.emit({id:e,type:"removed"})}))}notifyCommandChanged(e){if(void 0!==e&&!this._commands.has(e))throw new Error(`Command '${e}' is not registered.`);this._commandChanged.emit({id:e,type:e?"changed":"many-changed"})}describedBy(e,t=h.JSONExt.emptyObject){var n;let i=this._commands.get(e);return Promise.resolve(null!==(n=null==i?void 0:i.describedBy.call(void 0,t))&&void 0!==n?n:{args:null})}label(e,t=h.JSONExt.emptyObject){var n;let i=this._commands.get(e);return null!==(n=null==i?void 0:i.label.call(void 0,t))&&void 0!==n?n:""}mnemonic(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.mnemonic.call(void 0,t):-1}icon(e,t=h.JSONExt.emptyObject){var n;return null===(n=this._commands.get(e))||void 0===n?void 0:n.icon.call(void 0,t)}iconClass(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconClass.call(void 0,t):""}iconLabel(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconLabel.call(void 0,t):""}caption(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.caption.call(void 0,t):""}usage(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.usage.call(void 0,t):""}className(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.className.call(void 0,t):""}dataset(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.dataset.call(void 0,t):{}}isEnabled(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isEnabled.call(void 0,t)}isToggled(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggled.call(void 0,t)}isToggleable(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggleable}isVisible(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isVisible.call(void 0,t)}execute(e,t=h.JSONExt.emptyObject){let n,i=this._commands.get(e);if(!i)return Promise.reject(new Error(`Command '${e}' not registered.`));try{n=i.execute.call(void 0,t)}catch(e){n=Promise.reject(e)}let s=Promise.resolve(n);return this._commandExecuted.emit({id:e,args:t,result:s}),s}addKeyBinding(e){let t=w.createKeyBinding(e);return this._keyBindings.push(t),this._keyBindingChanged.emit({binding:t,type:"added"}),new f((()=>{d.RO.removeFirstOf(this._keyBindings,t),this._keyBindingChanged.emit({binding:t,type:"removed"})}))}processKeydownEvent(e){if(this._replaying||E.isModifierKeyPressed(e))return;let t=E.keystrokeForKeydownEvent(e);if(!t)return this._replayKeydownEvents(),void this._clearPendingState();this._keystrokes.push(t);let{exact:n,partial:i}=w.matchKeyBinding(this._keyBindings,this._keystrokes,e);return n||i?(e.preventDefault(),e.stopPropagation(),n&&!i?(this._executeKeyBinding(n),void this._clearPendingState()):(n&&(this._exactKeyMatch=n),this._keydownEvents.push(e),void this._startTimer())):(this._replayKeydownEvents(),void this._clearPendingState())}_startTimer(){this._clearTimer(),this._timerID=window.setTimeout((()=>{this._onPendingTimeout()}),w.CHORD_TIMEOUT)}_clearTimer(){0!==this._timerID&&(clearTimeout(this._timerID),this._timerID=0)}_replayKeydownEvents(){0!==this._keydownEvents.length&&(this._replaying=!0,this._keydownEvents.forEach(w.replayKeyEvent),this._replaying=!1)}_executeKeyBinding(e){let{command:t,args:n}=e,i={_luminoEvent:{type:"keybinding",keys:e.keys},...n};if(this.hasCommand(t)&&this.isEnabled(t,i))this.execute(t,i);else{let n=this.hasCommand(t)?"enabled":"registered",i=`Cannot execute key binding '${e.keys.join(", ")}':`,s=`command '${t}' is not ${n}.`;console.warn(`${i} ${s}`)}}_clearPendingState(){this._clearTimer(),this._exactKeyMatch=null,this._keystrokes.length=0,this._keydownEvents.length=0}_onPendingTimeout(){this._timerID=0,this._exactKeyMatch?this._executeKeyBinding(this._exactKeyMatch):this._replayKeydownEvents(),this._clearPendingState()}}function*S(){}function A(e,t){let n=0;for(const i of e)if(t(i,n++))return i}!function(e){function t(e){let t="",n=!1,i=!1,s=!1,o=!1;for(let a of e.split(/\s+/))"Accel"===a?r.IS_MAC?i=!0:s=!0:"Alt"===a?n=!0:"Cmd"===a?i=!0:"Ctrl"===a?s=!0:"Shift"===a?o=!0:a.length>0&&(t=a);return{cmd:i,ctrl:s,alt:n,shift:o,key:t}}function n(e){let n="",i=t(e);return i.ctrl&&(n+="Ctrl "),i.alt&&(n+="Alt "),i.shift&&(n+="Shift "),i.cmd&&r.IS_MAC&&(n+="Cmd "),n+i.key}e.parseKeystroke=t,e.normalizeKeystroke=n,e.normalizeKeys=function(e){let t;return t=r.IS_WIN?e.winKeys||e.keys:r.IS_MAC?e.macKeys||e.keys:e.linuxKeys||e.keys,t.map(n)},e.formatKeystroke=function(e){return"string"==typeof e?n(e):e.map(n).join(", ");function n(e){let n=[],i=r.IS_MAC?" ":"+",s=t(e);return s.ctrl&&n.push("Ctrl"),s.alt&&n.push("Alt"),s.shift&&n.push("Shift"),r.IS_MAC&&s.cmd&&n.push("Cmd"),n.push(s.key),n.map(w.formatKey).join(i)}},e.isModifierKeyPressed=function(e){let t=v(),n=t.keyForKeydownEvent(e);return t.isModifierKey(n)},e.keystrokeForKeydownEvent=function(e){let t=v(),n=t.keyForKeydownEvent(e);if(!n||t.isModifierKey(n))return"";let i=[];return e.ctrlKey&&i.push("Ctrl"),e.altKey&&i.push("Alt"),e.shiftKey&&i.push("Shift"),e.metaKey&&r.IS_MAC&&i.push("Cmd"),i.push(n),i.join(" ")}}(E||(E={})),function(e){e.CHORD_TIMEOUT=1e3,e.createCommand=function(e){return{execute:e.execute,describedBy:d("function"==typeof e.describedBy?e.describedBy:{args:null,...e.describedBy},(()=>({args:null}))),label:d(e.label,i),mnemonic:d(e.mnemonic,s),icon:d(e.icon,u),iconClass:d(e.iconClass,i),iconLabel:d(e.iconLabel,i),caption:d(e.caption,i),usage:d(e.usage,i),className:d(e.className,i),dataset:d(e.dataset,c),isEnabled:e.isEnabled||a,isToggled:e.isToggled||l,isToggleable:e.isToggleable||!!e.isToggled,isVisible:e.isVisible||a}},e.createKeyBinding=function(e){return{keys:E.normalizeKeys(e),selector:p(e),command:e.command,args:e.args||h.JSONExt.emptyObject}},e.matchKeyBinding=function(e,t,n){let i=null,s=!1,r=1/0,a=0;for(let l=0,c=e.length;lr)continue;let h=o.calculateSpecificity(c.selector);(!i||d=a)&&(i=c,r=d,a=h)}return{exact:i,partial:s}},e.replayKeyEvent=function(e){e.target.dispatchEvent(function(e){let t=document.createEvent("Event"),n=e.bubbles||!0,i=e.cancelable||!0;return t.initEvent(e.type||"keydown",n,i),t.key=e.key||"",t.keyCode=e.keyCode||0,t.which=e.keyCode||0,t.ctrlKey=e.ctrlKey||!1,t.altKey=e.altKey||!1,t.shiftKey=e.shiftKey||!1,t.metaKey=e.metaKey||!1,t.view=e.view||window,t}(e))},e.formatKey=function(e){return r.IS_MAC?t.hasOwnProperty(e)?t[e]:e:n.hasOwnProperty(e)?n[e]:e};const t={Backspace:"⌫",Tab:"⇥",Enter:"⏎",Shift:"⇧",Ctrl:"⌃",Alt:"⌥",Escape:"⎋",PageUp:"⇞",PageDown:"⇟",End:"↘",Home:"↖",ArrowLeft:"←",ArrowUp:"↑",ArrowRight:"→",ArrowDown:"↓",Delete:"⌦",Cmd:"⌘"},n={Escape:"Esc",PageUp:"Page Up",PageDown:"Page Down",ArrowLeft:"Left",ArrowUp:"Up",ArrowRight:"Right",ArrowDown:"Down",Delete:"Del"},i=()=>"",s=()=>-1,a=()=>!0,l=()=>!1,c=()=>({}),u=()=>{};function d(e,t){return void 0===e?t:"function"==typeof e?e:()=>e}function p(e){if(-1!==e.selector.indexOf(","))throw new Error(`Selector cannot contain commas: ${e.selector}`);if(!o.isValid(e.selector))throw new Error(`Invalid selector: ${e.selector}`);return e.selector}function f(e,t){if(e.lengtht.length?2:1}function m(e,t){let n=t.target,i=t.currentTarget;for(let t=0;null!==n;n=n.parentElement,++t){if(n.hasAttribute("data-lm-suppress-shortcuts"))return-1;if(o.matches(n,e))return t;if(n===i)return-1}return-1}}(w||(w={})),function(e){function t(e,t,n=0,i=-1){let s,r=e.length;if(0===r)return-1;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(D||(D={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(C||(C={}));var k,M,F,I,O,P,B,R,T,L,j,N=n(8743);!function(e){e.copyText=function(e){const t=document.body,n=i=>{i.preventDefault(),i.stopPropagation(),i.clipboardData.setData("text",e),t.removeEventListener("copy",n,!0)};t.addEventListener("copy",n,!0),document.execCommand("copy")}}(k||(k={})),function(e){e.boxSizing=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,i=parseFloat(t.borderLeftWidth)||0,s=parseFloat(t.borderRightWidth)||0,r=parseFloat(t.borderBottomWidth)||0,o=parseFloat(t.paddingTop)||0,a=parseFloat(t.paddingLeft)||0,l=parseFloat(t.paddingRight)||0,c=parseFloat(t.paddingBottom)||0;return{borderTop:n,borderLeft:i,borderRight:s,borderBottom:r,paddingTop:o,paddingLeft:a,paddingRight:l,paddingBottom:c,horizontalSum:i+a+l+s,verticalSum:n+o+c+r}},e.sizeLimits=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.minWidth)||0,i=parseFloat(t.minHeight)||0,s=parseFloat(t.maxWidth)||1/0,r=parseFloat(t.maxHeight)||1/0;return s=Math.max(n,s),r=Math.max(i,r),{minWidth:n,minHeight:i,maxWidth:s,maxHeight:r}},e.hitTest=function(e,t,n){let i=e.getBoundingClientRect();return t>=i.left&&t=i.top&&n=n.bottom||(i.topn.bottom&&i.height>=n.height?e.scrollTop-=n.top-i.top:(i.topn.height||i.bottom>n.bottom&&i.height{let e=Element.prototype;return e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(e){let t=this,n=t.ownerDocument?t.ownerDocument.querySelectorAll(e):[];return-1!==Array.prototype.indexOf.call(n,t)}})(),e.calculateSingle=function(e){let c=0,u=0,d=0;function h(t){let n=e.match(t);return null!==n&&(e=e.slice(n[0].length),!0)}for(e=(e=e.split(",",1)[0]).replace(l," $1 ");e.length>0;)if(h(t))c++;else if(h(n))u++;else if(h(i))u++;else if(h(r))d++;else if(h(o))u++;else if(h(s))d++;else if(!h(a))return 0;return c=Math.min(c,255),u=Math.min(u,255),d=Math.min(d,255),c<<16|u<<8|d};const t=/^#[^\s\+>~#\.\[:]+/,n=/^\.[^\s\+>~#\.\[:]+/,i=/^\[[^\]]+\]/,s=/^[^\s\+>~#\.\[:]+/,r=/^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/,o=/^:[^\s\+>~#\.\[:]+/,a=/^[\s\+>~\*]+/,l=/:not\(([^\)]+)\)/g}(O||(O={}));class z{constructor(){this._first=null,this._last=null,this._size=0}get isEmpty(){return 0===this._size}get size(){return this._size}get length(){return this._size}get first(){return this._first?this._first.value:void 0}get last(){return this._last?this._last.value:void 0}get firstNode(){return this._first}get lastNode(){return this._last}*[Symbol.iterator](){let e=this._first;for(;e;)yield e.value,e=e.next}*retro(){let e=this._last;for(;e;)yield e.value,e=e.prev}*nodes(){let e=this._first;for(;e;)yield e,e=e.next}*retroNodes(){let e=this._last;for(;e;)yield e,e=e.prev}assign(e){this.clear();for(const t of e)this.addLast(t)}push(e){this.addLast(e)}pop(){return this.removeLast()}shift(e){this.addFirst(e)}unshift(){return this.removeFirst()}addFirst(e){let t=new P.LinkedListNode(this,e);return this._first?(t.next=this._first,this._first.prev=t,this._first=t):(this._first=t,this._last=t),this._size++,t}addLast(e){let t=new P.LinkedListNode(this,e);return this._last?(t.prev=this._last,this._last.next=t,this._last=t):(this._first=t,this._last=t),this._size++,t}insertBefore(e,t){if(!t||t===this._first)return this.addFirst(e);if(!(t instanceof P.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");let n=new P.LinkedListNode(this,e),i=t,s=i.prev;return n.next=i,n.prev=s,i.prev=n,s.next=n,this._size++,n}insertAfter(e,t){if(!t||t===this._last)return this.addLast(e);if(!(t instanceof P.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");let n=new P.LinkedListNode(this,e),i=t,s=i.next;return n.next=s,n.prev=i,i.next=n,s.prev=n,this._size++,n}removeFirst(){let e=this._first;if(e)return e===this._last?(this._first=null,this._last=null):(this._first=e.next,this._first.prev=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value}removeLast(){let e=this._last;if(e)return e===this._first?(this._first=null,this._last=null):(this._last=e.prev,this._last.next=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value}removeNode(e){if(!(e instanceof P.LinkedListNode)||e.list!==this)throw new Error("Node is not owned by the list.");let t=e;t===this._first&&t===this._last?(this._first=null,this._last=null):t===this._first?(this._first=t.next,this._first.prev=null):t===this._last?(this._last=t.prev,this._last.next=null):(t.next.prev=t.prev,t.prev.next=t.next),t.list=null,t.next=null,t.prev=null,this._size--}clear(){let e=this._first;for(;e;){let t=e.next;e.list=null,e.prev=null,e.next=null,e=t}this._first=null,this._last=null,this._size=0}}!function(e){e.from=function(t){let n=new e;return n.assign(t),n}}(z||(z={})),function(e){e.LinkedListNode=class{constructor(e,t){this.list=null,this.next=null,this.prev=null,this.list=e,this.value=t}}}(P||(P={}));class U{constructor(e){this.type=e}get isConflatable(){return!1}conflate(e){return!1}}class q extends U{get isConflatable(){return!0}conflate(e){return!0}}!function(e){let t=null;const n=(i=Promise.resolve(),e=>{let t=!1;return i.then((()=>!t&&e())),()=>{t=!0}});var i;function s(e,t){let n=o.get(e);if(!n||0===n.length)return void u(e,t);let i=function(e,t){let n=0;for(const i of e)if(!1===t(i,n++))return!1;return!0}(function*(e){if("function"==typeof e.retro)yield*e.retro();else for(let t=e.length-1;t>-1;t--)yield e[t]}(n),(n=>!n||function(e,t,n){let i=!0;try{i="function"==typeof e?e(t,n):e.messageHook(t,n)}catch(e){l(e)}return i}(n,e,t)));i&&u(e,t)}e.sendMessage=s,e.postMessage=function(e,t){t.isConflatable&&function(n,i){for(const i of n)if((s=i).handler===e&&s.msg&&s.msg.type===t.type&&s.msg.isConflatable&&s.msg.conflate(t))return!0;var s;return!1}(r)||d(e,t)},e.installMessageHook=function(e,t){let n=o.get(e);n&&-1!==n.indexOf(t)||(n?n.push(t):o.set(e,[t]))},e.removeMessageHook=function(e,t){let n=o.get(e);if(!n)return;let i=n.indexOf(t);-1!==i&&(n[i]=null,p(n))},e.clearData=function(e){let t=o.get(e);t&&t.length>0&&(D.fill(t,null),p(t));for(const t of r)t.handler===e&&(t.handler=null,t.msg=null)},e.flush=function(){c||null===t||(t(),t=null,c=!0,h(),c=!1)},e.getExceptionHandler=function(){return l},e.setExceptionHandler=function(e){let t=l;return l=e,t};const r=new z,o=new WeakMap,a=new Set;let l=e=>{console.error(e)},c=!1;function u(e,t){try{e.processMessage(t)}catch(e){l(e)}}function d(e,i){r.addLast({handler:e,msg:i}),null===t&&(t=n(h))}function h(){if(t=null,r.isEmpty)return;let e={handler:null,msg:null};for(r.addLast(e);;){let t=r.removeFirst();if(t===e)return;t.handler&&t.msg&&s(t.handler,t.msg)}}function p(e){0===a.size&&n(f),a.add(e)}function f(){a.forEach(m),a.clear()}function m(e){D.removeAllWhere(e,g)}function g(e){return null===e}}(B||(B={}));class W{constructor(e){this._pid=R.nextPID(),this.name=e.name,this._create=e.create,this._coerce=e.coerce||null,this._compare=e.compare||null,this._changed=e.changed||null}get(e){let t,n=R.ensureMap(e);return t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e),t}set(e,t){let n,i=R.ensureMap(e);n=this._pid in i?i[this._pid]:i[this._pid]=this._createValue(e);let s=this._coerceValue(e,t);this._maybeNotify(e,n,i[this._pid]=s)}coerce(e){let t,n=R.ensureMap(e);t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e);let i=this._coerceValue(e,t);this._maybeNotify(e,t,n[this._pid]=i)}_createValue(e){return(0,this._create)(e)}_coerceValue(e,t){let n=this._coerce;return n?n(e,t):t}_compareValue(e,t){let n=this._compare;return n?n(e,t):e===t}_maybeNotify(e,t,n){let i=this._changed;i&&!this._compareValue(t,n)&&i(e,t,n)}}!function(e){e.clearData=function(e){R.ownerData.delete(e)}}(W||(W={})),function(e){e.ownerData=new WeakMap,e.nextPID=(()=>{let e=0;return()=>`pid-${`${Math.random()}`.slice(2)}-${e++}`})(),e.ensureMap=function(t){let n=e.ownerData.get(t);return n||(n=Object.create(null),e.ownerData.set(t,n),n)}}(R||(R={}));class H{constructor(e){this.sender=e}connect(e,t){return T.connect(this,e,t)}disconnect(e,t){return T.disconnect(this,e,t)}emit(e){T.emit(this,e)}}(j=H||(H={})).disconnectBetween=function(e,t){T.disconnectBetween(e,t)},j.disconnectSender=function(e){T.disconnectSender(e)},j.disconnectReceiver=function(e){T.disconnectReceiver(e)},j.disconnectAll=function(e){T.disconnectAll(e)},j.clearData=function(e){T.disconnectAll(e)},j.getExceptionHandler=function(){return T.exceptionHandler},j.setExceptionHandler=function(e){let t=T.exceptionHandler;return T.exceptionHandler=e,t};class K extends(null){constructor(){super(...arguments),this._pending=new PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new PromiseDelegate}}!function(e){function t(e){let t=i.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,c(s.get(t))}c(t)}}function n(e){let t=s.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,c(i.get(t))}c(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let r=i.get(e.sender);if(r||(r=[],i.set(e.sender,r)),a(r,e,t,n))return!1;let o=n||t,l=s.get(o);l||(l=[],s.set(o,l));let c={signal:e,slot:t,thisArg:n};return r.push(c),l.push(c),!0},e.disconnect=function(e,t,n){n=n||void 0;let r=i.get(e.sender);if(!r||0===r.length)return!1;let o=a(r,e,t,n);if(!o)return!1;let l=n||t,u=s.get(l);return o.signal=null,c(r),c(u),!0},e.disconnectBetween=function(e,t){let n=i.get(e);if(!n||0===n.length)return;let r=s.get(t);if(r&&0!==r.length){for(const t of r)t.signal&&t.signal.sender===e&&(t.signal=null);c(n),c(r)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=i.get(e.sender);if(n&&0!==n.length)for(let i=0,s=n.length;ie.signal===t&&e.slot===n&&e.thisArg===i))}function l(t,n){let{signal:i,slot:s,thisArg:r}=t;try{s.call(r,i.sender,n)}catch(t){e.exceptionHandler(t)}}function c(e){0===r.size&&o(u),r.add(e)}function u(){r.forEach(d),r.clear()}function d(e){D.removeAllWhere(e,h)}function h(e){return null===e.signal}}(T||(T={}));class ${constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class V{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(V||(V={}));class J extends V{constructor(){super(...arguments),this._disposed=new H(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),H.clearData(this))}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(J||(J={}));class G{constructor(e){this._onScrollFrame=()=>{if(!this._scrollTarget)return;let{element:e,edge:t,distance:n}=this._scrollTarget,i=L.SCROLL_EDGE_SIZE-n,s=Math.pow(i/L.SCROLL_EDGE_SIZE,2),r=Math.max(1,Math.round(s*L.SCROLL_EDGE_SIZE));switch(t){case"top":e.scrollTop-=r;break;case"left":e.scrollLeft-=r;break;case"right":e.scrollLeft+=r;break;case"bottom":e.scrollTop+=r}requestAnimationFrame(this._onScrollFrame)},this._disposed=!1,this._dropAction="none",this._override=null,this._currentTarget=null,this._currentElement=null,this._promise=null,this._scrollTarget=null,this._resolve=null,this.document=e.document||document,this.mimeData=e.mimeData,this.dragImage=e.dragImage||null,this.proposedAction=e.proposedAction||"copy",this.supportedActions=e.supportedActions||"all",this.source=e.source||null}dispose(){if(!this._disposed){if(this._disposed=!0,this._currentTarget){let e=new PointerEvent("pointerup",{bubbles:!0,cancelable:!0,clientX:-1,clientY:-1});L.dispatchDragLeave(this,this._currentTarget,null,e)}this._finalize("none")}}get isDisposed(){return this._disposed}start(e,t){if(this._disposed)return Promise.resolve("none");if(this._promise)return this._promise;this._addListeners(),this._attachDragImage(e,t),this._promise=new Promise((e=>{this._resolve=e}));let n=new PointerEvent("pointermove",{bubbles:!0,cancelable:!0,clientX:e,clientY:t});return document.dispatchEvent(n),this._promise}handleEvent(e){switch(e.type){case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;default:e.preventDefault(),e.stopPropagation()}}moveDragImage(e,t){this.dragImage&&(this.dragImage.style.transform=`translate(${e}px, ${t}px)`)}_evtPointerMove(e){e.preventDefault(),e.stopPropagation(),this._updateCurrentTarget(e),this._updateDragScroll(e),this.moveDragImage(e.clientX,e.clientY)}_evtPointerUp(e){if(e.preventDefault(),e.stopPropagation(),0!==e.button)return;if(this._updateCurrentTarget(e),!this._currentTarget)return void this._finalize("none");if("none"===this._dropAction)return L.dispatchDragLeave(this,this._currentTarget,null,e),void this._finalize("none");let t=L.dispatchDrop(this,this._currentTarget,e);this._finalize(t)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation(),27===e.keyCode&&this.dispose()}_addListeners(){document.addEventListener("pointerdown",this,!0),document.addEventListener("pointermove",this,!0),document.addEventListener("pointerup",this,!0),document.addEventListener("pointerenter",this,!0),document.addEventListener("pointerleave",this,!0),document.addEventListener("pointerover",this,!0),document.addEventListener("pointerout",this,!0),document.addEventListener("keydown",this,!0),document.addEventListener("keyup",this,!0),document.addEventListener("keypress",this,!0),document.addEventListener("contextmenu",this,!0)}_removeListeners(){document.removeEventListener("pointerdown",this,!0),document.removeEventListener("pointermove",this,!0),document.removeEventListener("pointerup",this,!0),document.removeEventListener("pointerenter",this,!0),document.removeEventListener("pointerleave",this,!0),document.removeEventListener("pointerover",this,!0),document.removeEventListener("pointerout",this,!0),document.removeEventListener("keydown",this,!0),document.removeEventListener("keyup",this,!0),document.removeEventListener("keypress",this,!0),document.removeEventListener("contextmenu",this,!0)}_updateDragScroll(e){let t=L.findScrollTarget(e);(this._scrollTarget||t)&&(this._scrollTarget||setTimeout(this._onScrollFrame,500),this._scrollTarget=t)}_updateCurrentTarget(e){let t=this._currentTarget,n=this._currentTarget,i=this._currentElement,s=L.findElementBehindBackdrop(e,this.document);this._currentElement=s,s!==i&&s!==n&&L.dispatchDragExit(this,n,s,e),s!==i&&s!==n&&(n=L.dispatchDragEnter(this,s,n,e)),n!==t&&(this._currentTarget=n,L.dispatchDragLeave(this,t,n,e));let r=L.dispatchDragOver(this,n,e);this._setDropAction(r)}_attachDragImage(e,t){if(!this.dragImage)return;this.dragImage.classList.add("lm-mod-drag-image");let n=this.dragImage.style;n.pointerEvents="none",n.position="fixed",n.transform=`translate(${e}px, ${t}px)`,(this.document instanceof Document?this.document.body:this.document.firstElementChild).appendChild(this.dragImage)}_detachDragImage(){if(!this.dragImage)return;let e=this.dragImage.parentNode;e&&e.removeChild(this.dragImage)}_setDropAction(e){if(e=L.validateAction(e,this.supportedActions),!this._override||this._dropAction!==e)switch(e){case"none":this._dropAction=e,this._override=G.overrideCursor("no-drop",this.document);break;case"copy":this._dropAction=e,this._override=G.overrideCursor("copy",this.document);break;case"link":this._dropAction=e,this._override=G.overrideCursor("alias",this.document);break;case"move":this._dropAction=e,this._override=G.overrideCursor("move",this.document)}}_finalize(e){let t=this._resolve;this._removeListeners(),this._detachDragImage(),this._override&&(this._override.dispose(),this._override=null),this.mimeData.clear(),this._disposed=!0,this._dropAction="none",this._currentTarget=null,this._currentElement=null,this._scrollTarget=null,this._promise=null,this._resolve=null,t&&t(e)}}function Y(){return Q.keyboardLayout}!function(e){class t extends DragEvent{constructor(e,t){super(t.type,{bubbles:!0,cancelable:!0,altKey:e.altKey,button:e.button,clientX:e.clientX,clientY:e.clientY,ctrlKey:e.ctrlKey,detail:0,metaKey:e.metaKey,relatedTarget:t.related,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window});const{drag:n}=t;this.dropAction="none",this.mimeData=n.mimeData,this.proposedAction=n.proposedAction,this.supportedActions=n.supportedActions,this.source=n.source}}e.Event=t,e.overrideCursor=function(e,t=document){return L.overrideCursor(e,t)}}(G||(G={})),function(e){function t(t,s=document){if(t){if(n&&t==n.event)return n.element;e.cursorBackdrop.style.zIndex="-1000";const i=s.elementFromPoint(t.clientX,t.clientY);return e.cursorBackdrop.style.zIndex="",n={event:t,element:i},i}{const t=e.cursorBackdrop.style.transform;if(i&&t===i.transform)return i.element;const n=e.cursorBackdrop.getBoundingClientRect();e.cursorBackdrop.style.zIndex="-1000";const r=s.elementFromPoint(n.left+n.width/2,n.top+n.height/2);return e.cursorBackdrop.style.zIndex="",i={transform:t,element:r},r}}e.SCROLL_EDGE_SIZE=20,e.validateAction=function(e,t){return s[e]&r[t]?e:"none"},e.findElementBehindBackdrop=t;let n=null,i=null;e.findScrollTarget=function(n){let i=n.clientX,s=n.clientY,r=t(n);for(;r;r=r.parentElement){if(!r.hasAttribute("data-lm-dragscroll"))continue;let t=0,n=0;r===document.body&&(t=window.pageXOffset,n=window.pageYOffset);let o=r.getBoundingClientRect(),a=o.top+n,l=o.left+t,c=l+o.width,u=a+o.height;if(i=c||s=u)continue;let d,h=i-l+1,p=s-a+1,f=c-i,m=u-s,g=Math.min(h,p,f,m);if(g>e.SCROLL_EDGE_SIZE)continue;switch(g){case m:d="bottom";break;case p:d="top";break;case f:d="right";break;case h:d="left";break;default:throw"unreachable"}let v,_=r.scrollWidth-r.clientWidth,y=r.scrollHeight-r.clientHeight;switch(d){case"top":v=y>0&&r.scrollTop>0;break;case"left":v=_>0&&r.scrollLeft>0;break;case"right":v=_>0&&r.scrollLeft<_;break;case"bottom":v=y>0&&r.scrollTop{i===u&&e.cursorBackdrop.isConnected&&(document.removeEventListener("pointermove",o,!0),e.cursorBackdrop.removeEventListener("scroll",a,!0),s.removeChild(e.cursorBackdrop))}))};const c=500;let u=0;e.cursorBackdrop=function(){const e=document.createElement("div");return e.classList.add("lm-cursor-backdrop"),e}()}(L||(L={}));class X{constructor(e,t,n=[]){this.name=e,this._codes=t,this._keys=X.extractKeys(t),this._modifierKeys=X.convertToKeySet(n)}keys(){return Object.keys(this._keys)}isValidKey(e){return e in this._keys}isModifierKey(e){return e in this._modifierKeys}keyForKeydownEvent(e){return this._codes[e.keyCode]||""}}!function(e){e.extractKeys=function(e){let t=Object.create(null);for(let n in e)t[e[n]]=!0;return t},e.convertToKeySet=function(e){let t=Object(null);for(let n=0,i=e.length;n{this._commands.delete(e),this._commandChanged.emit({id:e,type:"removed"})}))}notifyCommandChanged(e){if(void 0!==e&&!this._commands.has(e))throw new Error(`Command '${e}' is not registered.`);this._commandChanged.emit({id:e,type:e?"changed":"many-changed"})}describedBy(e,t=N.JSONExt.emptyObject){var n;let i=this._commands.get(e);return Promise.resolve(null!==(n=null==i?void 0:i.describedBy.call(void 0,t))&&void 0!==n?n:{args:null})}label(e,t=N.JSONExt.emptyObject){var n;let i=this._commands.get(e);return null!==(n=null==i?void 0:i.label.call(void 0,t))&&void 0!==n?n:""}mnemonic(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.mnemonic.call(void 0,t):-1}icon(e,t=N.JSONExt.emptyObject){var n;return null===(n=this._commands.get(e))||void 0===n?void 0:n.icon.call(void 0,t)}iconClass(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconClass.call(void 0,t):""}iconLabel(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconLabel.call(void 0,t):""}caption(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.caption.call(void 0,t):""}usage(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.usage.call(void 0,t):""}className(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.className.call(void 0,t):""}dataset(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.dataset.call(void 0,t):{}}isEnabled(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isEnabled.call(void 0,t)}isToggled(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggled.call(void 0,t)}isToggleable(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggleable}isVisible(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isVisible.call(void 0,t)}execute(e,t=N.JSONExt.emptyObject){let n,i=this._commands.get(e);if(!i)return Promise.reject(new Error(`Command '${e}' not registered.`));try{n=i.execute.call(void 0,t)}catch(e){n=Promise.reject(e)}let s=Promise.resolve(n);return this._commandExecuted.emit({id:e,args:t,result:s}),s}addKeyBinding(e){let t=ee.createKeyBinding(e);return this._keyBindings.push(t),this._keyBindingChanged.emit({binding:t,type:"added"}),new $((()=>{D.removeFirstOf(this._keyBindings,t),this._keyBindingChanged.emit({binding:t,type:"removed"})}))}processKeydownEvent(e){if(this._replaying||ae.isModifierKeyPressed(e))return;let t=ae.keystrokeForKeydownEvent(e);if(!t)return this._replayKeydownEvents(),void this._clearPendingState();this._keystrokes.push(t);let{exact:n,partial:i}=ee.matchKeyBinding(this._keyBindings,this._keystrokes,e);return n||i?(e.preventDefault(),e.stopPropagation(),n&&!i?(this._executeKeyBinding(n),void this._clearPendingState()):(n&&(this._exactKeyMatch=n),this._keydownEvents.push(e),void this._startTimer())):(this._replayKeydownEvents(),void this._clearPendingState())}_startTimer(){this._clearTimer(),this._timerID=window.setTimeout((()=>{this._onPendingTimeout()}),ee.CHORD_TIMEOUT)}_clearTimer(){0!==this._timerID&&(clearTimeout(this._timerID),this._timerID=0)}_replayKeydownEvents(){0!==this._keydownEvents.length&&(this._replaying=!0,this._keydownEvents.forEach(ee.replayKeyEvent),this._replaying=!1)}_executeKeyBinding(e){let{command:t,args:n}=e,i={_luminoEvent:{type:"keybinding",keys:e.keys},...n};if(this.hasCommand(t)&&this.isEnabled(t,i))this.execute(t,i);else{let n=this.hasCommand(t)?"enabled":"registered",i=`Cannot execute key binding '${e.keys.join(", ")}':`,s=`command '${t}' is not ${n}.`;console.warn(`${i} ${s}`)}}_clearPendingState(){this._clearTimer(),this._exactKeyMatch=null,this._keystrokes.length=0,this._keydownEvents.length=0}_onPendingTimeout(){this._timerID=0,this._exactKeyMatch?this._executeKeyBinding(this._exactKeyMatch):this._replayKeydownEvents(),this._clearPendingState()}}!function(e){function t(e){let t="",n=!1,i=!1,s=!1,r=!1;for(let o of e.split(/\s+/))"Accel"===o?F.IS_MAC?i=!0:s=!0:"Alt"===o?n=!0:"Cmd"===o?i=!0:"Ctrl"===o?s=!0:"Shift"===o?r=!0:o.length>0&&(t=o);return{cmd:i,ctrl:s,alt:n,shift:r,key:t}}function n(e){let n="",i=t(e);return i.ctrl&&(n+="Ctrl "),i.alt&&(n+="Alt "),i.shift&&(n+="Shift "),i.cmd&&F.IS_MAC&&(n+="Cmd "),n+i.key}e.parseKeystroke=t,e.normalizeKeystroke=n,e.normalizeKeys=function(e){let t;return t=F.IS_WIN?e.winKeys||e.keys:F.IS_MAC?e.macKeys||e.keys:e.linuxKeys||e.keys,t.map(n)},e.formatKeystroke=function(e){return"string"==typeof e?n(e):e.map(n).join(", ");function n(e){let n=[],i=F.IS_MAC?" ":"+",s=t(e);return s.ctrl&&n.push("Ctrl"),s.alt&&n.push("Alt"),s.shift&&n.push("Shift"),F.IS_MAC&&s.cmd&&n.push("Cmd"),n.push(s.key),n.map(ee.formatKey).join(i)}},e.isModifierKeyPressed=function(e){let t=Y(),n=t.keyForKeydownEvent(e);return t.isModifierKey(n)},e.keystrokeForKeydownEvent=function(e){let t=Y(),n=t.keyForKeydownEvent(e);if(!n||t.isModifierKey(n))return"";let i=[];return e.ctrlKey&&i.push("Ctrl"),e.altKey&&i.push("Alt"),e.shiftKey&&i.push("Shift"),e.metaKey&&F.IS_MAC&&i.push("Cmd"),i.push(n),i.join(" ")}}(ae||(ae={})),function(e){e.CHORD_TIMEOUT=1e3,e.createCommand=function(e){return{execute:e.execute,describedBy:c("function"==typeof e.describedBy?e.describedBy:{args:null,...e.describedBy},(()=>({args:null}))),label:c(e.label,i),mnemonic:c(e.mnemonic,s),icon:c(e.icon,l),iconClass:c(e.iconClass,i),iconLabel:c(e.iconLabel,i),caption:c(e.caption,i),usage:c(e.usage,i),className:c(e.className,i),dataset:c(e.dataset,a),isEnabled:e.isEnabled||r,isToggled:e.isToggled||o,isToggleable:e.isToggleable||!!e.isToggled,isVisible:e.isVisible||r}},e.createKeyBinding=function(e){return{keys:ae.normalizeKeys(e),selector:u(e),command:e.command,args:e.args||N.JSONExt.emptyObject}},e.matchKeyBinding=function(e,t,n){let i=null,s=!1,r=1/0,o=0;for(let a=0,l=e.length;ar)continue;let p=I.calculateSpecificity(l.selector);(!i||u=o)&&(i=l,r=u,o=p)}return{exact:i,partial:s}},e.replayKeyEvent=function(e){e.target.dispatchEvent(function(e){let t=document.createEvent("Event"),n=e.bubbles||!0,i=e.cancelable||!0;return t.initEvent(e.type||"keydown",n,i),t.key=e.key||"",t.keyCode=e.keyCode||0,t.which=e.keyCode||0,t.ctrlKey=e.ctrlKey||!1,t.altKey=e.altKey||!1,t.shiftKey=e.shiftKey||!1,t.metaKey=e.metaKey||!1,t.view=e.view||window,t}(e))},e.formatKey=function(e){return F.IS_MAC?t.hasOwnProperty(e)?t[e]:e:n.hasOwnProperty(e)?n[e]:e};const t={Backspace:"⌫",Tab:"⇥",Enter:"⏎",Shift:"⇧",Ctrl:"⌃",Alt:"⌥",Escape:"⎋",PageUp:"⇞",PageDown:"⇟",End:"↘",Home:"↖",ArrowLeft:"←",ArrowUp:"↑",ArrowRight:"→",ArrowDown:"↓",Delete:"⌦",Cmd:"⌘"},n={Escape:"Esc",PageUp:"Page Up",PageDown:"Page Down",ArrowLeft:"Left",ArrowUp:"Up",ArrowRight:"Right",ArrowDown:"Down",Delete:"Del"},i=()=>"",s=()=>-1,r=()=>!0,o=()=>!1,a=()=>({}),l=()=>{};function c(e,t){return void 0===e?t:"function"==typeof e?e:()=>e}function u(e){if(-1!==e.selector.indexOf(","))throw new Error(`Selector cannot contain commas: ${e.selector}`);if(!I.isValid(e.selector))throw new Error(`Invalid selector: ${e.selector}`);return e.selector}function d(e,t){if(e.lengtht.length?2:1}function h(e,t){let n=t.target,i=t.currentTarget;for(let t=0;null!==n;n=n.parentElement,++t){if(n.hasAttribute("data-lm-suppress-shortcuts"))return-1;if(I.matches(n,e))return t;if(n===i)return-1}return-1}}(ee||(ee={}));class le{constructor(e){this.type="text",this.content=e}}class ce{constructor(e,t,n,i){this.type="element",this.tag=e,this.attrs=t,this.children=n,this.renderer=i}}function ue(e){let t,n={},i=[];for(let e=1,r=arguments.length;e=i;--r){const i=t[r],o=s?e.lastChild:e.childNodes[r];"text"===i.type||(i.renderer&&i.renderer.unrender?i.renderer.unrender(o,{attrs:i.attrs,children:i.children}):n(o,i.children,0,!1)),s&&e.removeChild(o)}}e.hostMap=new WeakMap,e.asContentArray=function(e){return e?e instanceof Array?e:[e]:[]},e.createDOMNode=t,e.updateContent=function e(i,r,o){if(r===o)return;let a=function(e,t){let n=e.firstChild,i=Object.create(null);for(let e of t)"element"===e.type&&e.attrs.key&&(i[e.attrs.key]={vNode:e,element:n}),n=n.nextSibling;return i}(i,r),l=r.slice(),c=i.firstChild,u=o.length;for(let n=0;n=l.length){t(o[n],i);continue}let r=l[n],u=o[n];if(r===u){c=c.nextSibling;continue}if("text"===r.type&&"text"===u.type){c.textContent!==u.content&&(c.textContent=u.content),c=c.nextSibling;continue}if("text"===r.type||"text"===u.type){D.insert(l,n,u),t(u,i,c);continue}if(!r.renderer!=!u.renderer){D.insert(l,n,u),t(u,i,c);continue}let d=u.attrs.key;if(d&&d in a){let e=a[d];e.vNode!==r&&(D.move(l,l.indexOf(e.vNode,n+1),n),i.insertBefore(e.element,c),r=e.vNode,c=e.element)}if(r===u){c=c.nextSibling;continue}let h=r.attrs.key;h&&h!==d?(D.insert(l,n,u),t(u,i,c)):r.tag===u.tag?(s(c,r.attrs,u.attrs),u.renderer?u.renderer.render(c,{attrs:u.attrs,children:u.children}):e(c,r.children,u.children),c=c.nextSibling):(D.insert(l,n,u),t(u,i,c))}n(i,l,u,!0)};const i={key:!0,className:!0,htmlFor:!0,dataset:!0,style:!0};function s(e,t,n){if(t===n)return;let s;for(s in t)s in i||s in n||("on"===s.substr(0,2)?e[s]=null:e.removeAttribute(s));for(s in n)s in i||t[s]===n[s]||("on"===s.substr(0,2)?e[s]=n[s]:e.setAttribute(s,n[s]));t.className!==n.className&&(void 0!==n.className?e.setAttribute("class",n.className):e.removeAttribute("class")),t.htmlFor!==n.htmlFor&&(void 0!==n.htmlFor?e.setAttribute("for",n.htmlFor):e.removeAttribute("for")),t.dataset!==n.dataset&&function(e,t,n){for(let i in t)i in n||e.removeAttribute(`data-${i}`);for(let i in n)t[i]!==n[i]&&e.setAttribute(`data-${i}`,n[i])}(e,t.dataset||{},n.dataset||{}),t.style!==n.style&&function(e,t,n){let i,s=e.style;for(i in t)i in n||(s[i]="");for(i in n)t[i]!==n[i]&&(s[i]=n[i])}(e,t.style||{},n.style||{})}}(ne||(ne={}));class de{constructor(){this.sizeHint=0,this.minSize=0,this.maxSize=1/0,this.stretch=1,this.size=0,this.done=!1}}!function(e){e.calc=function(e,t){let n=e.length;if(0===n)return t;let i=0,s=0,r=0,o=0,a=0;for(let t=0;t0&&(o+=n.stretch,a++)}if(t===r)return 0;if(t<=i){for(let t=0;t=s){for(let t=0;t0&&i>l;){let t=i,s=o;for(let r=0;r0&&i>l;){let t=i/c;for(let s=0;s0&&i>l;){let t=i,s=o;for(let r=0;r=n.maxSize?(i-=n.maxSize-n.size,o-=n.stretch,n.size=n.maxSize,n.done=!0,c--,a--):(i-=l,n.size+=l)}}for(;c>0&&i>l;){let t=i/c;for(let s=0;s=n.maxSize?(i-=n.maxSize-n.size,n.size=n.maxSize,n.done=!0,c--):(i-=t,n.size+=t))}}}return 0},e.adjust=function(e,t,n){0!==e.length&&0!==n&&(n>0?function(e,t,n){let i=0;for(let n=0;n<=t;++n){let t=e[n];i+=t.maxSize-t.size}let s=0;for(let n=t+1,i=e.length;n=0&&r>0;--n){let t=e[n],i=t.maxSize-t.size;i>=r?(t.sizeHint=t.size+r,r=0):(t.sizeHint=t.size+i,r-=i)}let o=n;for(let n=t+1,i=e.length;n0;++n){let t=e[n],i=t.size-t.minSize;i>=o?(t.sizeHint=t.size-o,o=0):(t.sizeHint=t.size-i,o-=i)}}(e,t,n):function(e,t,n){let i=0;for(let n=t+1,s=e.length;n0;++n){let t=e[n],i=t.maxSize-t.size;i>=r?(t.sizeHint=t.size+r,r=0):(t.sizeHint=t.size+i,r-=i)}let o=n;for(let n=t;n>=0&&o>0;--n){let t=e[n],i=t.size-t.minSize;i>=o?(t.sizeHint=t.size-o,o=0):(t.sizeHint=t.size-i,o-=i)}}(e,t,-n))}}(ie||(ie={}));class he{constructor(e){this._label="",this._caption="",this._mnemonic=-1,this._icon=void 0,this._iconClass="",this._iconLabel="",this._className="",this._closable=!1,this._changed=new H(this),this._isDisposed=!1,this.owner=e.owner,void 0!==e.label&&(this._label=e.label),void 0!==e.mnemonic&&(this._mnemonic=e.mnemonic),void 0!==e.icon&&(this._icon=e.icon),void 0!==e.iconClass&&(this._iconClass=e.iconClass),void 0!==e.iconLabel&&(this._iconLabel=e.iconLabel),void 0!==e.caption&&(this._caption=e.caption),void 0!==e.className&&(this._className=e.className),void 0!==e.closable&&(this._closable=e.closable),this._dataset=e.dataset||{}}get changed(){return this._changed}get label(){return this._label}set label(e){this._label!==e&&(this._label=e,this._changed.emit(void 0))}get mnemonic(){return this._mnemonic}set mnemonic(e){this._mnemonic!==e&&(this._mnemonic=e,this._changed.emit(void 0))}get icon(){return this._icon}set icon(e){this._icon!==e&&(this._icon=e,this._changed.emit(void 0))}get iconClass(){return this._iconClass}set iconClass(e){this._iconClass!==e&&(this._iconClass=e,this._changed.emit(void 0))}get iconLabel(){return this._iconLabel}set iconLabel(e){this._iconLabel!==e&&(this._iconLabel=e,this._changed.emit(void 0))}get caption(){return this._caption}set caption(e){this._caption!==e&&(this._caption=e,this._changed.emit(void 0))}get className(){return this._className}set className(e){this._className!==e&&(this._className=e,this._changed.emit(void 0))}get closable(){return this._closable}set closable(e){this._closable!==e&&(this._closable=e,this._changed.emit(void 0))}get dataset(){return this._dataset}set dataset(e){this._dataset!==e&&(this._dataset=e,this._changed.emit(void 0))}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,H.clearData(this))}}class pe{constructor(e={}){this._flags=0,this._layout=null,this._parent=null,this._disposed=new H(this),this._hiddenMode=pe.HiddenMode.Display,this.node=se.createNode(e),this.addClass("lm-Widget")}dispose(){this.isDisposed||(this.setFlag(pe.Flag.IsDisposed),this._disposed.emit(void 0),this.parent?this.parent=null:this.isAttached&&pe.detach(this),this._layout&&(this._layout.dispose(),this._layout=null),this.title.dispose(),H.clearData(this),B.clearData(this),W.clearData(this))}get disposed(){return this._disposed}get isDisposed(){return this.testFlag(pe.Flag.IsDisposed)}get isAttached(){return this.testFlag(pe.Flag.IsAttached)}get isHidden(){return this.testFlag(pe.Flag.IsHidden)}get isVisible(){return this.testFlag(pe.Flag.IsVisible)}get title(){return se.titleProperty.get(this)}get id(){return this.node.id}set id(e){this.node.id=e}get dataset(){return this.node.dataset}get hiddenMode(){return this._hiddenMode}set hiddenMode(e){this._hiddenMode!==e&&(this.isHidden&&this._toggleHidden(!1),e==pe.HiddenMode.Scale?this.node.style.willChange="transform":this.node.style.willChange="auto",this._hiddenMode=e,this.isHidden&&this._toggleHidden(!0))}get parent(){return this._parent}set parent(e){if(this._parent!==e){if(e&&this.contains(e))throw new Error("Invalid parent widget.");if(this._parent&&!this._parent.isDisposed){let e=new pe.ChildMessage("child-removed",this);B.sendMessage(this._parent,e)}if(this._parent=e,this._parent&&!this._parent.isDisposed){let e=new pe.ChildMessage("child-added",this);B.sendMessage(this._parent,e)}this.isDisposed||B.sendMessage(this,pe.Msg.ParentChanged)}}get layout(){return this._layout}set layout(e){if(this._layout!==e){if(this.testFlag(pe.Flag.DisallowLayout))throw new Error("Cannot set widget layout.");if(this._layout)throw new Error("Cannot change widget layout.");if(e.parent)throw new Error("Cannot change layout parent.");this._layout=e,e.parent=this}}*children(){this._layout&&(yield*this._layout)}contains(e){for(let t=e;t;t=t._parent)if(t===this)return!0;return!1}hasClass(e){return this.node.classList.contains(e)}addClass(e){this.node.classList.add(e)}removeClass(e){this.node.classList.remove(e)}toggleClass(e,t){return!0===t?(this.node.classList.add(e),!0):!1===t?(this.node.classList.remove(e),!1):this.node.classList.toggle(e)}update(){B.postMessage(this,pe.Msg.UpdateRequest)}fit(){B.postMessage(this,pe.Msg.FitRequest)}activate(){B.postMessage(this,pe.Msg.ActivateRequest)}close(){B.sendMessage(this,pe.Msg.CloseRequest)}show(){if(this.testFlag(pe.Flag.IsHidden)&&(!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.BeforeShow),this.clearFlag(pe.Flag.IsHidden),this._toggleHidden(!1),!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.AfterShow),this.parent)){let e=new pe.ChildMessage("child-shown",this);B.sendMessage(this.parent,e)}}hide(){if(!this.testFlag(pe.Flag.IsHidden)&&(!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.BeforeHide),this.setFlag(pe.Flag.IsHidden),this._toggleHidden(!0),!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.AfterHide),this.parent)){let e=new pe.ChildMessage("child-hidden",this);B.sendMessage(this.parent,e)}}setHidden(e){e?this.hide():this.show()}testFlag(e){return 0!=(this._flags&e)}setFlag(e){this._flags|=e}clearFlag(e){this._flags&=~e}processMessage(e){switch(e.type){case"resize":this.notifyLayout(e),this.onResize(e);break;case"update-request":this.notifyLayout(e),this.onUpdateRequest(e);break;case"fit-request":this.notifyLayout(e),this.onFitRequest(e);break;case"before-show":this.notifyLayout(e),this.onBeforeShow(e);break;case"after-show":this.setFlag(pe.Flag.IsVisible),this.notifyLayout(e),this.onAfterShow(e);break;case"before-hide":this.notifyLayout(e),this.onBeforeHide(e);break;case"after-hide":this.clearFlag(pe.Flag.IsVisible),this.notifyLayout(e),this.onAfterHide(e);break;case"before-attach":this.notifyLayout(e),this.onBeforeAttach(e);break;case"after-attach":this.isHidden||this.parent&&!this.parent.isVisible||this.setFlag(pe.Flag.IsVisible),this.setFlag(pe.Flag.IsAttached),this.notifyLayout(e),this.onAfterAttach(e);break;case"before-detach":this.notifyLayout(e),this.onBeforeDetach(e);break;case"after-detach":this.clearFlag(pe.Flag.IsVisible),this.clearFlag(pe.Flag.IsAttached),this.notifyLayout(e),this.onAfterDetach(e);break;case"activate-request":this.notifyLayout(e),this.onActivateRequest(e);break;case"close-request":this.notifyLayout(e),this.onCloseRequest(e);break;case"child-added":this.notifyLayout(e),this.onChildAdded(e);break;case"child-removed":this.notifyLayout(e),this.onChildRemoved(e);break;default:this.notifyLayout(e)}}notifyLayout(e){this._layout&&this._layout.processParentMessage(e)}onCloseRequest(e){this.parent?this.parent=null:this.isAttached&&pe.detach(this)}onResize(e){}onUpdateRequest(e){}onFitRequest(e){}onActivateRequest(e){}onBeforeShow(e){}onAfterShow(e){}onBeforeHide(e){}onAfterHide(e){}onBeforeAttach(e){}onAfterAttach(e){}onBeforeDetach(e){}onAfterDetach(e){}onChildAdded(e){}onChildRemoved(e){}_toggleHidden(e){if(e)switch(this._hiddenMode){case pe.HiddenMode.Display:this.addClass("lm-mod-hidden");break;case pe.HiddenMode.Scale:this.node.style.transform="scale(0)",this.node.setAttribute("aria-hidden","true");break;case pe.HiddenMode.ContentVisibility:this.node.style.contentVisibility="hidden",this.node.style.zIndex="-1"}else switch(this._hiddenMode){case pe.HiddenMode.Display:this.removeClass("lm-mod-hidden");break;case pe.HiddenMode.Scale:this.node.style.transform="",this.node.removeAttribute("aria-hidden");break;case pe.HiddenMode.ContentVisibility:this.node.style.contentVisibility="",this.node.style.zIndex=""}}}!function(e){var t,n,i;(t=e.HiddenMode||(e.HiddenMode={}))[t.Display=0]="Display",t[t.Scale=1]="Scale",t[t.ContentVisibility=2]="ContentVisibility",(n=e.Flag||(e.Flag={}))[n.IsDisposed=1]="IsDisposed",n[n.IsAttached=2]="IsAttached",n[n.IsHidden=4]="IsHidden",n[n.IsVisible=8]="IsVisible",n[n.DisallowLayout=16]="DisallowLayout",(i=e.Msg||(e.Msg={})).BeforeShow=new U("before-show"),i.AfterShow=new U("after-show"),i.BeforeHide=new U("before-hide"),i.AfterHide=new U("after-hide"),i.BeforeAttach=new U("before-attach"),i.AfterAttach=new U("after-attach"),i.BeforeDetach=new U("before-detach"),i.AfterDetach=new U("after-detach"),i.ParentChanged=new U("parent-changed"),i.UpdateRequest=new q("update-request"),i.FitRequest=new q("fit-request"),i.ActivateRequest=new q("activate-request"),i.CloseRequest=new q("close-request"),e.ChildMessage=class extends U{constructor(e,t){super(e),this.child=t}};class s extends U{constructor(e,t){super("resize"),this.width=e,this.height=t}}e.ResizeMessage=s,function(e){e.UnknownSize=new e(-1,-1)}(s=e.ResizeMessage||(e.ResizeMessage={})),e.attach=function(t,n,i=null){if(t.parent)throw new Error("Cannot attach a child widget.");if(t.isAttached||t.node.isConnected)throw new Error("Widget is already attached.");if(!n.isConnected)throw new Error("Host is not attached.");B.sendMessage(t,e.Msg.BeforeAttach),n.insertBefore(t.node,i),B.sendMessage(t,e.Msg.AfterAttach)},e.detach=function(t){if(t.parent)throw new Error("Cannot detach a child widget.");if(!t.isAttached||!t.node.isConnected)throw new Error("Widget is not attached.");B.sendMessage(t,e.Msg.BeforeDetach),t.node.parentNode.removeChild(t.node),B.sendMessage(t,e.Msg.AfterDetach)}}(pe||(pe={})),function(e){e.titleProperty=new W({name:"title",create:e=>new he({owner:e})}),e.createNode=function(e){return e.node||document.createElement(e.tag||"div")}}(se||(se={}));class fe{constructor(e={}){this._disposed=!1,this._parent=null,this._fitPolicy=e.fitPolicy||"set-min-size"}dispose(){this._parent=null,this._disposed=!0,H.clearData(this),W.clearData(this)}get isDisposed(){return this._disposed}get parent(){return this._parent}set parent(e){if(this._parent!==e){if(this._parent)throw new Error("Cannot change parent widget.");if(e.layout!==this)throw new Error("Invalid parent widget.");this._parent=e,this.init()}}get fitPolicy(){return this._fitPolicy}set fitPolicy(e){if(this._fitPolicy!==e&&(this._fitPolicy=e,this._parent)){let e=this._parent.node.style;e.minWidth="",e.minHeight="",e.maxWidth="",e.maxHeight="",this._parent.fit()}}processParentMessage(e){switch(e.type){case"resize":this.onResize(e);break;case"update-request":this.onUpdateRequest(e);break;case"fit-request":this.onFitRequest(e);break;case"before-show":this.onBeforeShow(e);break;case"after-show":this.onAfterShow(e);break;case"before-hide":this.onBeforeHide(e);break;case"after-hide":this.onAfterHide(e);break;case"before-attach":this.onBeforeAttach(e);break;case"after-attach":this.onAfterAttach(e);break;case"before-detach":this.onBeforeDetach(e);break;case"after-detach":this.onAfterDetach(e);break;case"child-removed":this.onChildRemoved(e);break;case"child-shown":this.onChildShown(e);break;case"child-hidden":this.onChildHidden(e)}}init(){for(const e of this)e.parent=this.parent}onResize(e){for(const e of this)B.sendMessage(e,pe.ResizeMessage.UnknownSize)}onUpdateRequest(e){for(const e of this)B.sendMessage(e,pe.ResizeMessage.UnknownSize)}onBeforeAttach(e){for(const t of this)B.sendMessage(t,e)}onAfterAttach(e){for(const t of this)B.sendMessage(t,e)}onBeforeDetach(e){for(const t of this)B.sendMessage(t,e)}onAfterDetach(e){for(const t of this)B.sendMessage(t,e)}onBeforeShow(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onAfterShow(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onBeforeHide(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onAfterHide(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onChildRemoved(e){this.removeWidget(e.child)}onFitRequest(e){}onChildShown(e){}onChildHidden(e){}}!function(e){e.getHorizontalAlignment=function(e){return re.horizontalAlignmentProperty.get(e)},e.setHorizontalAlignment=function(e,t){re.horizontalAlignmentProperty.set(e,t)},e.getVerticalAlignment=function(e){return re.verticalAlignmentProperty.get(e)},e.setVerticalAlignment=function(e,t){re.verticalAlignmentProperty.set(e,t)}}(fe||(fe={}));class me{constructor(e){this._top=NaN,this._left=NaN,this._width=NaN,this._height=NaN,this._minWidth=0,this._minHeight=0,this._maxWidth=1/0,this._maxHeight=1/0,this._disposed=!1,this.widget=e,this.widget.node.style.position="absolute",this.widget.node.style.contain="strict"}dispose(){if(this._disposed)return;this._disposed=!0;let e=this.widget.node.style;e.position="",e.top="",e.left="",e.width="",e.height="",e.contain=""}get minWidth(){return this._minWidth}get minHeight(){return this._minHeight}get maxWidth(){return this._maxWidth}get maxHeight(){return this._maxHeight}get isDisposed(){return this._disposed}get isHidden(){return this.widget.isHidden}get isVisible(){return this.widget.isVisible}get isAttached(){return this.widget.isAttached}fit(){let e=M.sizeLimits(this.widget.node);this._minWidth=e.minWidth,this._minHeight=e.minHeight,this._maxWidth=e.maxWidth,this._maxHeight=e.maxHeight}update(e,t,n,i){let s=Math.max(this._minWidth,Math.min(n,this._maxWidth)),r=Math.max(this._minHeight,Math.min(i,this._maxHeight));if(s"center",changed:t}),e.verticalAlignmentProperty=new W({name:"verticalAlignment",create:()=>"top",changed:t})}(re||(re={}));class ge extends fe{constructor(){super(...arguments),this._widgets=[]}dispose(){for(;this._widgets.length>0;)this._widgets.pop().dispose();super.dispose()}get widgets(){return this._widgets}*[Symbol.iterator](){yield*this._widgets}addWidget(e){this.insertWidget(this._widgets.length,e)}insertWidget(e,t){t.parent=this.parent;let n=this._widgets.indexOf(t),i=Math.max(0,Math.min(e,this._widgets.length));if(-1===n)return D.insert(this._widgets,i,t),void(this.parent&&this.attachWidget(i,t));i===this._widgets.length&&i--,n!==i&&(D.move(this._widgets,n,i),this.parent&&this.moveWidget(n,i,t))}removeWidget(e){this.removeWidgetAt(this._widgets.indexOf(e))}removeWidgetAt(e){let t=D.removeAt(this._widgets,e);t&&this.parent&&this.detachWidget(e,t)}init(){super.init();let e=0;for(const t of this)this.attachWidget(e++,t)}attachWidget(e,t){let n=this.parent.node.children[e];this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.insertBefore(t.node,n),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach)}moveWidget(e,t,n){this.parent.isAttached&&B.sendMessage(n,pe.Msg.BeforeDetach),this.parent.node.removeChild(n.node),this.parent.isAttached&&B.sendMessage(n,pe.Msg.AfterDetach);let i=this.parent.node.children[t];this.parent.isAttached&&B.sendMessage(n,pe.Msg.BeforeAttach),this.parent.node.insertBefore(n.node,i),this.parent.isAttached&&B.sendMessage(n,pe.Msg.AfterAttach)}detachWidget(e,t){this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach)}}!function(e){e.clampDimension=function(e){return Math.max(0,Math.floor(e))}}(oe||(oe={}));var ve,_e,ye,be,we,De,xe,Ce,Ee,Se,Ae=oe;class ke extends ge{constructor(e){super(),this.widgetOffset=0,this._fixed=0,this._spacing=4,this._dirty=!1,this._hasNormedSizes=!1,this._sizers=[],this._items=[],this._handles=[],this._box=null,this._alignment="start",this._orientation="horizontal",this.renderer=e.renderer,void 0!==e.orientation&&(this._orientation=e.orientation),void 0!==e.alignment&&(this._alignment=e.alignment),void 0!==e.spacing&&(this._spacing=oe.clampDimension(e.spacing))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,this._sizers.length=0,this._handles.length=0,super.dispose()}get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,this.parent&&(this.parent.dataset.orientation=e,this.parent.fit()))}get alignment(){return this._alignment}set alignment(e){this._alignment!==e&&(this._alignment=e,this.parent&&(this.parent.dataset.alignment=e,this.parent.update()))}get spacing(){return this._spacing}set spacing(e){e=oe.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}get handles(){return this._handles}absoluteSizes(){return this._sizers.map((e=>e.size))}relativeSizes(){return ve.normalize(this._sizers.map((e=>e.size)))}setRelativeSizes(e,t=!0){let n=this._sizers.length,i=e.slice(0,n);for(;i.length0&&(e.sizeHint=e.size);ie.adjust(this._sizers,e,n),this.parent&&this.parent.update()}}init(){this.parent.dataset.orientation=this.orientation,this.parent.dataset.alignment=this.alignment,super.init()}attachWidget(e,t){let n=new me(t),i=ve.createHandle(this.renderer),s=ve.averageSize(this._sizers),r=ve.createSizer(s);D.insert(this._items,e,n),D.insert(this._sizers,e,r),D.insert(this._handles,e,i),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.node.appendChild(i),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){D.move(this._items,e,t),D.move(this._sizers,e,t),D.move(this._handles,e,t),this.parent.fit()}detachWidget(e,t){let n=D.removeAt(this._items,e),i=D.removeAt(this._handles,e);D.removeAt(this._sizers,e),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.node.removeChild(i),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}updateItemPosition(e,t,n,i,s,r,o){const a=this._items[e];if(a.isHidden)return;let l=this._handles[e].style;t?(n+=this.widgetOffset,a.update(n,i,o,s),n+=o,l.top=`${i}px`,l.left=`${n}px`,l.width=`${this._spacing}px`,l.height=`${s}px`):(i+=this.widgetOffset,a.update(n,i,r,o),i+=o,l.top=`${i}px`,l.left=`${n}px`,l.width=`${r}px`,l.height=`${this._spacing}px`)}_fit(){let e=0,t=-1;for(let n=0,i=this._items.length;n0&&(r.sizeHint=r.size),t.isHidden?(r.minSize=0,r.maxSize=0):(t.fit(),r.stretch=ke.getStretch(t.widget),n?(r.minSize=t.minWidth,r.maxSize=t.maxWidth,i+=t.minWidth,s=Math.max(s,t.minHeight)):(r.minSize=t.minHeight,r.maxSize=t.maxHeight,s+=t.minHeight,i=Math.max(i,t.minWidth)))}let r=this._box=M.boxSizing(this.parent.node);i+=r.horizontalSum,s+=r.verticalSum;let o=this.parent.node.style;o.minWidth=`${i}px`,o.minHeight=`${s}px`,this._dirty=!0,this.parent.parent&&B.sendMessage(this.parent.parent,pe.Msg.FitRequest),this._dirty&&B.sendMessage(this.parent,pe.Msg.UpdateRequest)}_update(e,t){this._dirty=!1;let n=0;for(let e=0,t=this._items.length;e0){let e;if(e=c?Math.max(0,r-this._fixed):Math.max(0,o-this._fixed),this._hasNormedSizes){for(let t of this._sizers)t.sizeHint*=e;this._hasNormedSizes=!1}let t=ie.calc(this._sizers,e);if(t>0)switch(this._alignment){case"start":break;case"center":a=0,l=t/2;break;case"end":a=0,l=t;break;case"justify":a=t/n,l=0;break;default:throw"unreachable"}}for(let e=0,t=this._items.length;e0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:function(e){e.parent&&e.parent.layout instanceof ke&&e.parent.fit()}}),e.createSizer=function(e){let t=new de;return t.sizeHint=Math.floor(e),t},e.createHandle=function(e){let t=e.createHandle();return t.style.position="absolute",t.style.contain="style",t},e.averageSize=function(e){return e.reduce(((e,t)=>e+t.size),0)/e.length||0},e.normalize=function(e){let t=e.length;if(0===t)return[];let n=e.reduce(((e,t)=>e+Math.abs(t)),0);return 0===n?e.map((e=>1/t)):e.map((e=>e/n))}}(ve||(ve={}));class Me extends ke{constructor(e){super({...e,orientation:e.orientation||"vertical"}),this._titles=[],this.titleSpace=e.titleSpace||22}get titleSpace(){return this.widgetOffset}set titleSpace(e){e=Ae.clampDimension(e),this.widgetOffset!==e&&(this.widgetOffset=e,this.parent&&this.parent.fit())}get titles(){return this._titles}dispose(){this.isDisposed||(this._titles.length=0,super.dispose())}updateTitle(e,t){const n=this._titles[e],i=n.classList.contains("lm-mod-expanded"),s=_e.createTitle(this.renderer,t.title,i);this._titles[e]=s,this.parent.node.replaceChild(s,n)}insertWidget(e,t){t.id||(t.id=`id-${N.UUID.uuid4()}`),super.insertWidget(e,t)}attachWidget(e,t){const n=_e.createTitle(this.renderer,t.title);D.insert(this._titles,e,n),this.parent.node.appendChild(n),t.node.setAttribute("role","region"),t.node.setAttribute("aria-labelledby",n.id),super.attachWidget(e,t)}moveWidget(e,t,n){D.move(this._titles,e,t),super.moveWidget(e,t,n)}detachWidget(e,t){const n=D.removeAt(this._titles,e);this.parent.node.removeChild(n),super.detachWidget(e,t)}updateItemPosition(e,t,n,i,s,r,o){const a=this._titles[e].style;a.top=`${i}px`,a.left=`${n}px`,a.height=`${this.widgetOffset}px`,a.width=t?`${s}px`:`${r}px`,super.updateItemPosition(e,t,n,i,s,r,o)}}!function(e){e.createTitle=function(e,t,n=!0){const i=e.createSectionTitle(t);return i.style.position="absolute",i.style.contain="strict",i.setAttribute("aria-label",`${t.label} Section`),i.setAttribute("aria-expanded",n?"true":"false"),i.setAttribute("aria-controls",t.owner.id),n&&i.classList.add("lm-mod-expanded"),i}}(_e||(_e={}));class Fe extends pe{constructor(e={}){super(),this.addClass("lm-Panel"),this.layout=ye.createLayout(e)}get widgets(){return this.layout.widgets}addWidget(e){this.layout.addWidget(e)}insertWidget(e,t){this.layout.insertWidget(e,t)}}!function(e){e.createLayout=function(e){return e.layout||new ge}}(ye||(ye={}));class Ie extends Fe{constructor(e={}){super({layout:be.createLayout(e)}),this._handleMoved=new H(this),this._pressData=null,this.addClass("lm-SplitPanel")}dispose(){this._releaseMouse(),super.dispose()}get orientation(){return this.layout.orientation}set orientation(e){this.layout.orientation=e}get alignment(){return this.layout.alignment}set alignment(e){this.layout.alignment=e}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}get renderer(){return this.layout.renderer}get handleMoved(){return this._handleMoved}get handles(){return this.layout.handles}relativeSizes(){return this.layout.relativeSizes()}setRelativeSizes(e,t=!0){this.layout.setRelativeSizes(e,t)}handleEvent(e){switch(e.type){case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("pointerdown",this)}onAfterDetach(e){this.node.removeEventListener("pointerdown",this),this._releaseMouse()}onChildAdded(e){e.child.addClass("lm-SplitPanel-child"),this._releaseMouse()}onChildRemoved(e){e.child.removeClass("lm-SplitPanel-child"),this._releaseMouse()}_evtKeyDown(e){this._pressData&&(e.preventDefault(),e.stopPropagation()),27===e.keyCode&&this._releaseMouse()}_evtPointerDown(e){if(0!==e.button)return;let t,n=this.layout,i=D.findFirstIndex(n.handles,(t=>t.contains(e.target)));if(-1===i)return;e.preventDefault(),e.stopPropagation(),document.addEventListener("pointerup",this,!0),document.addEventListener("pointermove",this,!0),document.addEventListener("keydown",this,!0),document.addEventListener("contextmenu",this,!0);let s=n.handles[i],r=s.getBoundingClientRect();t="horizontal"===n.orientation?e.clientX-r.left:e.clientY-r.top;let o=window.getComputedStyle(s),a=G.overrideCursor(o.cursor);this._pressData={index:i,delta:t,override:a}}_evtPointerMove(e){let t;e.preventDefault(),e.stopPropagation();let n=this.layout,i=this.node.getBoundingClientRect();t="horizontal"===n.orientation?e.clientX-i.left-this._pressData.delta:e.clientY-i.top-this._pressData.delta,n.moveHandle(this._pressData.index,t)}_evtPointerUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this._releaseMouse())}_releaseMouse(){this._pressData&&(this._pressData.override.dispose(),this._pressData=null,this._handleMoved.emit(),document.removeEventListener("keydown",this,!0),document.removeEventListener("pointerup",this,!0),document.removeEventListener("pointermove",this,!0),document.removeEventListener("contextmenu",this,!0))}}!function(e){class t{createHandle(){let e=document.createElement("div");return e.className="lm-SplitPanel-handle",e}}e.Renderer=t,e.defaultRenderer=new t,e.getStretch=function(e){return ke.getStretch(e)},e.setStretch=function(e,t){ke.setStretch(e,t)}}(Ie||(Ie={})),function(e){e.createLayout=function(e){return e.layout||new ke({renderer:e.renderer||Ie.defaultRenderer,orientation:e.orientation,alignment:e.alignment,spacing:e.spacing})}}(be||(be={}));class Oe extends Ie{constructor(e={}){super({...e,layout:we.createLayout(e)}),this._widgetSizesCache=new WeakMap,this._expansionToggled=new H(this),this.addClass("lm-AccordionPanel")}get renderer(){return this.layout.renderer}get titleSpace(){return this.layout.titleSpace}set titleSpace(e){this.layout.titleSpace=e}get titles(){return this.layout.titles}get expansionToggled(){return this._expansionToggled}addWidget(e){super.addWidget(e),e.title.changed.connect(this._onTitleChanged,this)}collapse(e){const t=this.layout.widgets[e];t&&!t.isHidden&&this._toggleExpansion(e)}expand(e){const t=this.layout.widgets[e];t&&t.isHidden&&this._toggleExpansion(e)}insertWidget(e,t){super.insertWidget(e,t),t.title.changed.connect(this._onTitleChanged,this)}handleEvent(e){switch(super.handleEvent(e),e.type){case"click":this._evtClick(e);break;case"keydown":this._eventKeyDown(e)}}onBeforeAttach(e){this.node.addEventListener("click",this),this.node.addEventListener("keydown",this),super.onBeforeAttach(e)}onAfterDetach(e){super.onAfterDetach(e),this.node.removeEventListener("click",this),this.node.removeEventListener("keydown",this)}_onTitleChanged(e){const t=D.findFirstIndex(this.widgets,(t=>t.contains(e.owner)));t>=0&&(this.layout.updateTitle(t,e.owner),this.update())}_computeWidgetSize(e){const t=this.layout,n=t.widgets[e];if(!n)return;const i=n.isHidden,s=t.absoluteSizes(),r=(i?-1:1)*this.spacing,o=s.reduce(((e,t)=>e+t));let a=[...s];if(i){const t=this._widgetSizesCache.get(n);if(!t)return;a[e]+=t;const i=a.map((e=>e-t>0)).lastIndexOf(!0);-1===i?a.forEach(((n,i)=>{i!==e&&(a[i]-=s[i]/o*(t-r))})):a[i]-=t-r}else{const t=s[e];this._widgetSizesCache.set(n,t),a[e]=0;const i=a.map((e=>e>0)).lastIndexOf(!0);if(-1===i)return;a[i]=s[i]+t+r}return a.map((e=>e/(o+r)))}_evtClick(e){const t=e.target;if(t){const n=D.findFirstIndex(this.titles,(e=>e.contains(t)));n>=0&&(e.preventDefault(),e.stopPropagation(),this._toggleExpansion(n))}}_eventKeyDown(e){if(e.defaultPrevented)return;const t=e.target;let n=!1;if(t){const i=D.findFirstIndex(this.titles,(e=>e.contains(t)));if(i>=0){const s=e.keyCode.toString();if(e.key.match(/Space|Enter/)||s.match(/13|32/))t.click(),n=!0;else if("horizontal"===this.orientation?e.key.match(/ArrowLeft|ArrowRight/)||s.match(/37|39/):e.key.match(/ArrowUp|ArrowDown/)||s.match(/38|40/)){const t=e.key.match(/ArrowLeft|ArrowUp/)||s.match(/37|38/)?-1:1,r=this.titles.length,o=(i+r+t)%r;this.titles[o].focus(),n=!0}else"End"===e.key||"35"===s?(this.titles[this.titles.length-1].focus(),n=!0):"Home"!==e.key&&"36"!==s||(this.titles[0].focus(),n=!0)}n&&e.preventDefault()}}_toggleExpansion(e){const t=this.titles[e],n=this.layout.widgets[e],i=this._computeWidgetSize(e);i&&this.setRelativeSizes(i,!1),n.isHidden?(t.classList.add("lm-mod-expanded"),t.setAttribute("aria-expanded","true"),n.show()):(t.classList.remove("lm-mod-expanded"),t.setAttribute("aria-expanded","false"),n.hide()),this._expansionToggled.emit(e)}}!function(e){class t extends Ie.Renderer{constructor(){super(),this.titleClassName="lm-AccordionPanel-title",this._titleID=0,this._titleKeys=new WeakMap,this._uuid=++t._nInstance}createCollapseIcon(e){return document.createElement("span")}createSectionTitle(e){const t=document.createElement("h3");t.setAttribute("tabindex","0"),t.id=this.createTitleKey(e),t.className=this.titleClassName;for(const n in e.dataset)t.dataset[n]=e.dataset[n];t.appendChild(this.createCollapseIcon(e)).className="lm-AccordionPanel-titleCollapser";const n=t.appendChild(document.createElement("span"));return n.className="lm-AccordionPanel-titleLabel",n.textContent=e.label,n.title=e.caption||e.label,t}createTitleKey(e){let t=this._titleKeys.get(e);return void 0===t&&(t=`title-key-${this._uuid}-${this._titleID++}`,this._titleKeys.set(e,t)),t}}t._nInstance=0,e.Renderer=t,e.defaultRenderer=new t}(Oe||(Oe={})),function(e){e.createLayout=function(e){return e.layout||new Me({renderer:e.renderer||Oe.defaultRenderer,orientation:e.orientation,alignment:e.alignment,spacing:e.spacing,titleSpace:e.titleSpace})}}(we||(we={}));class Pe extends ge{constructor(e={}){super(),this._fixed=0,this._spacing=4,this._dirty=!1,this._sizers=[],this._items=[],this._box=null,this._alignment="start",this._direction="top-to-bottom",void 0!==e.direction&&(this._direction=e.direction),void 0!==e.alignment&&(this._alignment=e.alignment),void 0!==e.spacing&&(this._spacing=Ae.clampDimension(e.spacing))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,this._sizers.length=0,super.dispose()}get direction(){return this._direction}set direction(e){this._direction!==e&&(this._direction=e,this.parent&&(this.parent.dataset.direction=e,this.parent.fit()))}get alignment(){return this._alignment}set alignment(e){this._alignment!==e&&(this._alignment=e,this.parent&&(this.parent.dataset.alignment=e,this.parent.update()))}get spacing(){return this._spacing}set spacing(e){e=Ae.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}init(){this.parent.dataset.direction=this.direction,this.parent.dataset.alignment=this.alignment,super.init()}attachWidget(e,t){D.insert(this._items,e,new me(t)),D.insert(this._sizers,e,new de),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){D.move(this._items,e,t),D.move(this._sizers,e,t),this.parent.update()}detachWidget(e,t){let n=D.removeAt(this._items,e);D.removeAt(this._sizers,e),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){let e=0;for(let t=0,n=this._items.length;t0)switch(this._alignment){case"start":break;case"center":l=0,c=i/2;break;case"end":l=0,c=i;break;case"justify":l=i/n,c=0;break;default:throw"unreachable"}for(let e=0,t=this._items.length;e0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:t}),e.sizeBasisProperty=new W({name:"sizeBasis",create:()=>0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:t}),e.isHorizontal=function(e){return"left-to-right"===e||"right-to-left"===e},e.clampSpacing=function(e){return Math.max(0,Math.floor(e))}}(De||(De={}));class Be extends Fe{constructor(e={}){super({layout:xe.createLayout(e)}),this.addClass("lm-BoxPanel")}get direction(){return this.layout.direction}set direction(e){this.layout.direction=e}get alignment(){return this.layout.alignment}set alignment(e){this.layout.alignment=e}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}onChildAdded(e){e.child.addClass("lm-BoxPanel-child")}onChildRemoved(e){e.child.removeClass("lm-BoxPanel-child")}}!function(e){e.getStretch=function(e){return Pe.getStretch(e)},e.setStretch=function(e,t){Pe.setStretch(e,t)},e.getSizeBasis=function(e){return Pe.getSizeBasis(e)},e.setSizeBasis=function(e,t){Pe.setSizeBasis(e,t)}}(Be||(Be={})),function(e){e.createLayout=function(e){return e.layout||new Pe(e)}}(xe||(xe={}));class Re extends pe{constructor(e){super({node:Ce.createNode()}),this._activeIndex=-1,this._items=[],this._results=null,this.addClass("lm-CommandPalette"),this.setFlag(pe.Flag.DisallowLayout),this.commands=e.commands,this.renderer=e.renderer||Re.defaultRenderer,this.commands.commandChanged.connect(this._onGenericChange,this),this.commands.keyBindingChanged.connect(this._onGenericChange,this)}dispose(){this._items.length=0,this._results=null,super.dispose()}get searchNode(){return this.node.getElementsByClassName("lm-CommandPalette-search")[0]}get inputNode(){return this.node.getElementsByClassName("lm-CommandPalette-input")[0]}get contentNode(){return this.node.getElementsByClassName("lm-CommandPalette-content")[0]}get items(){return this._items}addItem(e){let t=Ce.createItem(this.commands,e);return this._items.push(t),this.refresh(),t}addItems(e){const t=e.map((e=>Ce.createItem(this.commands,e)));return t.forEach((e=>this._items.push(e))),this.refresh(),t}removeItem(e){this.removeItemAt(this._items.indexOf(e))}removeItemAt(e){D.removeAt(this._items,e)&&this.refresh()}clearItems(){0!==this._items.length&&(this._items.length=0,this.refresh())}refresh(){this._results=null,""!==this.inputNode.value?this.node.getElementsByClassName("lm-close-icon")[0].style.display="inherit":this.node.getElementsByClassName("lm-close-icon")[0].style.display="none",this.update()}handleEvent(e){switch(e.type){case"click":this._evtClick(e);break;case"keydown":this._evtKeyDown(e);break;case"input":this.refresh();break;case"focus":case"blur":this._toggleFocused()}}onBeforeAttach(e){this.node.addEventListener("click",this),this.node.addEventListener("keydown",this),this.node.addEventListener("input",this),this.node.addEventListener("focus",this,!0),this.node.addEventListener("blur",this,!0)}onAfterDetach(e){this.node.removeEventListener("click",this),this.node.removeEventListener("keydown",this),this.node.removeEventListener("input",this),this.node.removeEventListener("focus",this,!0),this.node.removeEventListener("blur",this,!0)}onAfterShow(e){this.update(),super.onAfterShow(e)}onActivateRequest(e){if(this.isAttached){let e=this.inputNode;e.focus(),e.select()}}onUpdateRequest(e){if(this.isHidden)return;let t=this.inputNode.value,n=this.contentNode,i=this._results;if(i||(i=this._results=Ce.search(this._items,t),this._activeIndex=t?D.findFirstIndex(i,Ce.canActivate):-1),!t&&0===i.length)return void te.render(null,n);if(t&&0===i.length){let e=this.renderer.renderEmptyMessage({query:t});return void te.render(e,n)}let s=this.renderer,r=this._activeIndex,o=new Array(i.length);for(let e=0,t=i.length;e=i.length)n.scrollTop=0;else{let e=n.children[r];M.scrollIntoViewIfNeeded(n,e)}}_evtClick(e){if(0!==e.button)return;if(e.target.classList.contains("lm-close-icon"))return this.inputNode.value="",void this.refresh();let t=D.findFirstIndex(this.contentNode.children,(t=>t.contains(e.target)));-1!==t&&(e.preventDefault(),e.stopPropagation(),this._execute(t))}_evtKeyDown(e){if(!(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey))switch(e.keyCode){case 13:e.preventDefault(),e.stopPropagation(),this._execute(this._activeIndex);break;case 38:e.preventDefault(),e.stopPropagation(),this._activatePreviousItem();break;case 40:e.preventDefault(),e.stopPropagation(),this._activateNextItem()}}_activateNextItem(){if(!this._results||0===this._results.length)return;let e=this._activeIndex,t=this._results.length,n=ee-t)),c=r.slice(0,l),u=r.slice(l);for(let e=0,t=u.length;en.command===e&&N.JSONExt.deepEqual(n.args,t)))||null}}}(Ce||(Ce={}));class Te extends pe{constructor(e){super({node:Ee.createNode()}),this._childIndex=-1,this._activeIndex=-1,this._openTimerID=0,this._closeTimerID=0,this._items=[],this._childMenu=null,this._parentMenu=null,this._aboutToClose=new H(this),this._menuRequested=new H(this),this.addClass("lm-Menu"),this.setFlag(pe.Flag.DisallowLayout),this.commands=e.commands,this.renderer=e.renderer||Te.defaultRenderer}dispose(){this.close(),this._items.length=0,super.dispose()}get aboutToClose(){return this._aboutToClose}get menuRequested(){return this._menuRequested}get parentMenu(){return this._parentMenu}get childMenu(){return this._childMenu}get rootMenu(){let e=this;for(;e._parentMenu;)e=e._parentMenu;return e}get leafMenu(){let e=this;for(;e._childMenu;)e=e._childMenu;return e}get contentNode(){return this.node.getElementsByClassName("lm-Menu-content")[0]}get activeItem(){return this._items[this._activeIndex]||null}set activeItem(e){this.activeIndex=e?this._items.indexOf(e):-1}get activeIndex(){return this._activeIndex}set activeIndex(e){(e<0||e>=this._items.length)&&(e=-1),-1===e||Ee.canActivate(this._items[e])||(e=-1),this._activeIndex!==e&&(this._activeIndex=e,this._activeIndex>=0&&this.contentNode.childNodes[this._activeIndex]&&this.contentNode.childNodes[this._activeIndex].focus(),this.update())}get items(){return this._items}activateNextItem(){let e=this._items.length,t=this._activeIndex,n=t{this.activeIndex=e}})}te.render(r,this.contentNode)}onCloseRequest(e){this._cancelOpenTimer(),this._cancelCloseTimer(),this.activeIndex=-1;let t=this._childMenu;t&&(this._childIndex=-1,this._childMenu=null,t._parentMenu=null,t.close());let n=this._parentMenu;n&&(this._parentMenu=null,n._childIndex=-1,n._childMenu=null,n.activate()),this.isAttached&&this._aboutToClose.emit(void 0),super.onCloseRequest(e)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation();let t=e.keyCode;if(13===t)return void this.triggerActiveItem();if(27===t)return void this.close();if(37===t)return void(this._parentMenu?this.close():this._menuRequested.emit("previous"));if(38===t)return void this.activatePreviousItem();if(39===t){let e=this.activeItem;return void(e&&"submenu"===e.type?this.triggerActiveItem():this.rootMenu._menuRequested.emit("next"))}if(40===t)return void this.activateNextItem();let n=Y().keyForKeydownEvent(e);if(!n)return;let i=this._activeIndex+1,s=Ee.findMnemonic(this._items,n,i);-1===s.index||s.multiple?-1!==s.index?this.activeIndex=s.index:-1!==s.auto&&(this.activeIndex=s.auto):(this.activeIndex=s.index,this.triggerActiveItem())}_evtMouseUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this.triggerActiveItem())}_evtMouseMove(e){let t=D.findFirstIndex(this.contentNode.children,(t=>M.hitTest(t,e.clientX,e.clientY)));if(t===this._activeIndex)return;if(this.activeIndex=t,t=this.activeIndex,t===this._childIndex)return this._cancelOpenTimer(),void this._cancelCloseTimer();-1!==this._childIndex&&this._startCloseTimer(),this._cancelOpenTimer();let n=this.activeItem;n&&"submenu"===n.type&&n.submenu&&this._startOpenTimer()}_evtMouseEnter(e){for(let e=this._parentMenu;e;e=e._parentMenu)e._cancelOpenTimer(),e._cancelCloseTimer(),e.activeIndex=e._childIndex}_evtMouseLeave(e){if(this._cancelOpenTimer(),!this._childMenu)return void(this.activeIndex=-1);let{clientX:t,clientY:n}=e;M.hitTest(this._childMenu.node,t,n)?this._cancelCloseTimer():(this.activeIndex=-1,this._startCloseTimer())}_evtMouseDown(e){this._parentMenu||(Ee.hitTestMenus(this,e.clientX,e.clientY)?(e.preventDefault(),e.stopPropagation()):this.close())}_openChildMenu(e=!1){let t=this.activeItem;if(!t||"submenu"!==t.type||!t.submenu)return void this._closeChildMenu();let n=t.submenu;if(n===this._childMenu)return;Te.saveWindowData(),this._closeChildMenu(),this._childMenu=n,this._childIndex=this._activeIndex,n._parentMenu=this,B.sendMessage(this,pe.Msg.UpdateRequest);let i=this.contentNode.children[this._activeIndex];Ee.openSubmenu(n,i),e&&(n.activeIndex=-1,n.activateNextItem()),n.activate()}_closeChildMenu(){this._childMenu&&this._childMenu.close()}_startOpenTimer(){0===this._openTimerID&&(this._openTimerID=window.setTimeout((()=>{this._openTimerID=0,this._openChildMenu()}),Ee.TIMER_DELAY))}_startCloseTimer(){0===this._closeTimerID&&(this._closeTimerID=window.setTimeout((()=>{this._closeTimerID=0,this._closeChildMenu()}),Ee.TIMER_DELAY))}_cancelOpenTimer(){0!==this._openTimerID&&(clearTimeout(this._openTimerID),this._openTimerID=0)}_cancelCloseTimer(){0!==this._closeTimerID&&(clearTimeout(this._closeTimerID),this._closeTimerID=0)}static saveWindowData(){Ee.saveWindowData()}}!function(e){class t{renderItem(e){let t=this.createItemClass(e),n=this.createItemDataset(e),i=this.createItemARIA(e);return ue.li({className:t,dataset:n,tabindex:"0",onfocus:e.onfocus,...i},this.renderIcon(e),this.renderLabel(e),this.renderShortcut(e),this.renderSubmenu(e))}renderIcon(e){let t=this.createIconClass(e);return ue.div({className:t},e.item.icon,e.item.iconLabel)}renderLabel(e){let t=this.formatLabel(e);return ue.div({className:"lm-Menu-itemLabel"},t)}renderShortcut(e){let t=this.formatShortcut(e);return ue.div({className:"lm-Menu-itemShortcut"},t)}renderSubmenu(e){return ue.div({className:"lm-Menu-itemSubmenuIcon"})}createItemClass(e){let t="lm-Menu-item";e.item.isEnabled||(t+=" lm-mod-disabled"),e.item.isToggled&&(t+=" lm-mod-toggled"),e.item.isVisible||(t+=" lm-mod-hidden"),e.active&&(t+=" lm-mod-active"),e.collapsed&&(t+=" lm-mod-collapsed");let n=e.item.className;return n&&(t+=` ${n}`),t}createItemDataset(e){let t,{type:n,command:i,dataset:s}=e.item;return t="command"===n?{...s,type:n,command:i}:{...s,type:n},t}createIconClass(e){let t="lm-Menu-itemIcon",n=e.item.iconClass;return n?`${t} ${n}`:t}createItemARIA(e){let t={};switch(e.item.type){case"separator":t.role="presentation";break;case"submenu":t["aria-haspopup"]="true",e.item.isEnabled||(t["aria-disabled"]="true");break;default:e.item.isEnabled||(t["aria-disabled"]="true"),t.role="menuitem"}return t}formatLabel(e){let{label:t,mnemonic:n}=e.item;if(n<0||n>=t.length)return t;let i=t.slice(0,n),s=t.slice(n+1),r=t[n];return[i,ue.span({className:"lm-Menu-itemMnemonic"},r),s]}formatShortcut(e){let t=e.item.keyBinding;return t?ae.formatKeystroke(t.keys):null}}e.Renderer=t,e.defaultRenderer=new t}(Te||(Te={})),function(e){e.TIMER_DELAY=300,e.SUBMENU_OVERLAP=3;let t=null,n=0;function i(){return n>0?(n--,t):r()}function s(e){return"separator"!==e.type&&e.isEnabled&&e.isVisible}function r(){return{pageXOffset:window.pageXOffset,pageYOffset:window.pageYOffset,clientWidth:document.documentElement.clientWidth,clientHeight:document.documentElement.clientHeight}}e.saveWindowData=function(){t=r(),n++},e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");return t.className="lm-Menu-content",e.appendChild(t),t.setAttribute("role","menu"),e.tabIndex=0,e},e.canActivate=s,e.createItem=function(e,t){return new o(e.commands,t)},e.hitTestMenus=function(e,t,n){for(let i=e;i;i=i.childMenu)if(M.hitTest(i.node,t,n))return!0;return!1},e.computeCollapsed=function(e){let t=new Array(e.length);D.fill(t,!1);let n=0,i=e.length;for(;n=0;--s){let n=e[s];if(n.isVisible){if("separator"!==n.type)break;t[s]=!0}}let r=!1;for(;++na+c&&(t=a+c-f),!r&&n+m>l+u&&(n>l+u?n=l+u-m:n-=m),p.transform=`translate(${Math.max(0,t)}px, ${Math.max(0,n)}px`,p.opacity="1"},e.openSubmenu=function(t,n){const s=i();let r=s.pageXOffset,o=s.pageYOffset,a=s.clientWidth,l=s.clientHeight;B.sendMessage(t,pe.Msg.UpdateRequest);let c=l,u=t.node,d=u.style;d.opacity="0",d.maxHeight=`${c}px`,pe.attach(t,document.body);let{width:h,height:p}=u.getBoundingClientRect(),f=M.boxSizing(t.node),m=n.getBoundingClientRect(),g=m.right-e.SUBMENU_OVERLAP;g+h>r+a&&(g=m.left+e.SUBMENU_OVERLAP-h);let v=m.top-f.borderTop-f.paddingTop;v+p>o+l&&(v=m.bottom+f.borderBottom+f.paddingBottom-p),d.transform=`translate(${Math.max(0,g)}px, ${Math.max(0,v)}px`,d.opacity="1"},e.findMnemonic=function(e,t,n){let i=-1,r=-1,o=!1,a=t.toUpperCase();for(let t=0,l=e.length;t=0&&hn.command===e&&N.JSONExt.deepEqual(n.args,t)))||null}return null}}}(Ee||(Ee={}));class Le{constructor(e){this._groupByTarget=!0,this._idTick=0,this._items=[],this._sortBySelector=!0;const{groupByTarget:t,sortBySelector:n,...i}=e;this.menu=new Te(i),this._groupByTarget=!1!==t,this._sortBySelector=!1!==n}addItem(e){let t=Se.createItem(e,this._idTick++);return this._items.push(t),new $((()=>{D.removeFirstOf(this._items,t)}))}open(e){if(Te.saveWindowData(),this.menu.clearItems(),0===this._items.length)return!1;let t=Se.matchItems(this._items,e,this._groupByTarget,this._sortBySelector);if(!t||0===t.length)return!1;for(const e of t)this.menu.addItem(e);return this.menu.open(e.clientX,e.clientY),!0}}!function(e){function t(e,t){let n=e.rank,i=t.rank;return n!==i?n=this._titles.length)&&(e=-1),this._currentIndex===e)return;let t=this._currentIndex,n=this._titles[t]||null,i=e,s=this._titles[i]||null;this._currentIndex=i,this._previousTitle=n,this.update(),this._currentChanged.emit({previousIndex:t,previousTitle:n,currentIndex:i,currentTitle:s})}get name(){return this._name}set name(e){this._name=e,e?this.contentNode.setAttribute("aria-label",e):this.contentNode.removeAttribute("aria-label")}get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._releaseMouse(),this._orientation=e,this.dataset.orientation=e,this.contentNode.setAttribute("aria-orientation",e))}get addButtonEnabled(){return this._addButtonEnabled}set addButtonEnabled(e){this._addButtonEnabled!==e&&(this._addButtonEnabled=e,e?this.addButtonNode.classList.remove("lm-mod-hidden"):this.addButtonNode.classList.add("lm-mod-hidden"))}get titles(){return this._titles}get contentNode(){return this.node.getElementsByClassName("lm-TabBar-content")[0]}get addButtonNode(){return this.node.getElementsByClassName("lm-TabBar-addButton")[0]}addTab(e){return this.insertTab(this._titles.length,e)}insertTab(e,t){this._releaseMouse();let n=ze.asTitle(t),i=this._titles.indexOf(n),s=Math.max(0,Math.min(e,this._titles.length));return-1===i?(D.insert(this._titles,s,n),n.changed.connect(this._onTitleChanged,this),this.update(),this._adjustCurrentForInsert(s,n),n):(s===this._titles.length&&s--,i===s||(D.move(this._titles,i,s),this.update(),this._adjustCurrentForMove(i,s)),n)}removeTab(e){this.removeTabAt(this._titles.indexOf(e))}removeTabAt(e){this._releaseMouse();let t=D.removeAt(this._titles,e);t&&(t.changed.disconnect(this._onTitleChanged,this),t===this._previousTitle&&(this._previousTitle=null),this.update(),this._adjustCurrentForRemove(e,t))}clearTabs(){if(0===this._titles.length)return;this._releaseMouse();for(let e of this._titles)e.changed.disconnect(this._onTitleChanged,this);let e=this.currentIndex,t=this.currentTitle;this._currentIndex=-1,this._previousTitle=null,this._titles.length=0,this.update(),-1!==e&&this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null})}releaseMouse(){this._releaseMouse()}handleEvent(e){switch(e.type){case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"dblclick":this._evtDblClick(e);break;case"keydown":e.eventPhase===Event.CAPTURING_PHASE?this._evtKeyDownCapturing(e):this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("pointerdown",this),this.node.addEventListener("dblclick",this),this.node.addEventListener("keydown",this)}onAfterDetach(e){this.node.removeEventListener("pointerdown",this),this.node.removeEventListener("dblclick",this),this.node.removeEventListener("keydown",this),this._releaseMouse()}onUpdateRequest(e){var t;let n=this._titles,i=this.renderer,s=this.currentTitle,r=new Array(n.length);const o=null!==(t=this._getCurrentTabindex())&&void 0!==t?t:this._currentIndex>-1?this._currentIndex:0;for(let e=0,t=n.length;eM.hitTest(t,e.clientX,e.clientY)));if(-1===n)return;let i=this.titles[n],s=t[n].querySelector(".lm-TabBar-tabLabel");if(s&&s.contains(e.target)){let e=i.label||"",t=s.innerHTML;s.innerHTML="";let n=document.createElement("input");n.classList.add("lm-TabBar-tabInput"),n.value=e,s.appendChild(n);let r=()=>{n.removeEventListener("blur",r),s.innerHTML=t,this.node.addEventListener("keydown",this)};n.addEventListener("dblclick",(e=>e.stopPropagation())),n.addEventListener("blur",r),n.addEventListener("keydown",(e=>{"Enter"===e.key?(""!==n.value&&(i.label=i.caption=n.value),r()):"Escape"===e.key&&r()})),this.node.removeEventListener("keydown",this),n.select(),n.focus(),s.children.length>0&&s.children[0].focus()}}_evtKeyDownCapturing(e){e.eventPhase===Event.CAPTURING_PHASE&&(e.preventDefault(),e.stopPropagation(),"Escape"===e.key&&this._releaseMouse())}_evtKeyDown(e){var t,n,i;if("Tab"!==e.key&&e.eventPhase!==Event.CAPTURING_PHASE)if("Enter"===e.key||"Spacebar"===e.key||" "===e.key){const t=document.activeElement;if(this.addButtonEnabled&&this.addButtonNode.contains(t))e.preventDefault(),e.stopPropagation(),this._addRequested.emit();else{const n=D.findFirstIndex(this.contentNode.children,(e=>e.contains(t)));n>=0&&(e.preventDefault(),e.stopPropagation(),this.currentIndex=n)}}else if(je.includes(e.key)){const s=[...this.contentNode.children];if(this.addButtonEnabled&&s.push(this.addButtonNode),s.length<=1)return;e.preventDefault(),e.stopPropagation();let r,o=s.indexOf(document.activeElement);-1===o&&(o=this._currentIndex),"ArrowRight"===e.key&&"horizontal"===this._orientation||"ArrowDown"===e.key&&"vertical"===this._orientation?r=null!==(t=s[o+1])&&void 0!==t?t:s[0]:"ArrowLeft"===e.key&&"horizontal"===this._orientation||"ArrowUp"===e.key&&"vertical"===this._orientation?r=null!==(n=s[o-1])&&void 0!==n?n:s[s.length-1]:"Home"===e.key?r=s[0]:"End"===e.key&&(r=s[s.length-1]),r&&(null===(i=s[o])||void 0===i||i.setAttribute("tabindex","-1"),null==r||r.setAttribute("tabindex","0"),r.focus())}}_evtPointerDown(e){if(0!==e.button&&1!==e.button)return;if(this._dragData)return;if(e.target.classList.contains("lm-TabBar-tabInput"))return;let t=this.addButtonEnabled&&this.addButtonNode.contains(e.target),n=this.contentNode.children,i=D.findFirstIndex(n,(t=>M.hitTest(t,e.clientX,e.clientY)));if(-1===i&&!t)return;if(e.preventDefault(),e.stopPropagation(),this._dragData={tab:n[i],index:i,pressX:e.clientX,pressY:e.clientY,tabPos:-1,tabSize:-1,tabPressPos:-1,targetIndex:-1,tabLayout:null,contentRect:null,override:null,dragActive:!1,dragAborted:!1,detachRequested:!1},this.document.addEventListener("pointerup",this,!0),1===e.button||t)return;let s=n[i].querySelector(this.renderer.closeIconSelector);s&&s.contains(e.target)||(this.tabsMovable&&(this.document.addEventListener("pointermove",this,!0),this.document.addEventListener("keydown",this,!0),this.document.addEventListener("contextmenu",this,!0)),this.allowDeselect&&this.currentIndex===i?this.currentIndex=-1:this.currentIndex=i,-1!==this.currentIndex&&this._tabActivateRequested.emit({index:this.currentIndex,title:this.currentTitle}))}_evtPointerMove(e){let t=this._dragData;if(!t)return;e.preventDefault(),e.stopPropagation();let n=this.contentNode.children;if(t.dragActive||ze.dragExceeded(t,e)){if(!t.dragActive){let e=t.tab.getBoundingClientRect();"horizontal"===this._orientation?(t.tabPos=t.tab.offsetLeft,t.tabSize=e.width,t.tabPressPos=t.pressX-e.left):(t.tabPos=t.tab.offsetTop,t.tabSize=e.height,t.tabPressPos=t.pressY-e.top),t.tabPressOffset={x:t.pressX-e.left,y:t.pressY-e.top},t.tabLayout=ze.snapTabLayout(n,this._orientation),t.contentRect=this.contentNode.getBoundingClientRect(),t.override=G.overrideCursor("default"),t.tab.classList.add("lm-mod-dragging"),this.addClass("lm-mod-dragging"),t.dragActive=!0}if(!t.detachRequested&&ze.detachExceeded(t,e)){t.detachRequested=!0;let i=t.index,s=e.clientX,r=e.clientY,o=n[i],a=this._titles[i];if(this._tabDetachRequested.emit({index:i,title:a,tab:o,clientX:s,clientY:r,offset:t.tabPressOffset}),t.dragAborted)return}ze.layoutTabs(n,t,e,this._orientation)}}_evtPointerUp(e){if(0!==e.button&&1!==e.button)return;const t=this._dragData;if(!t)return;if(e.preventDefault(),e.stopPropagation(),this.document.removeEventListener("pointermove",this,!0),this.document.removeEventListener("pointerup",this,!0),this.document.removeEventListener("keydown",this,!0),this.document.removeEventListener("contextmenu",this,!0),!t.dragActive){if(this._dragData=null,this.addButtonEnabled&&this.addButtonNode.contains(e.target))return void this._addRequested.emit(void 0);let n=this.contentNode.children,i=D.findFirstIndex(n,(t=>M.hitTest(t,e.clientX,e.clientY)));if(i!==t.index)return;let s=this._titles[i];if(!s.closable)return;if(1===e.button)return void this._tabCloseRequested.emit({index:i,title:s});let r=n[i].querySelector(this.renderer.closeIconSelector);return r&&r.contains(e.target)?void this._tabCloseRequested.emit({index:i,title:s}):void 0}if(0!==e.button)return;ze.finalizeTabPosition(t,this._orientation),t.tab.classList.remove("lm-mod-dragging");let n=ze.parseTransitionDuration(t.tab);setTimeout((()=>{if(t.dragAborted)return;this._dragData=null,ze.resetTabPositions(this.contentNode.children,this._orientation),t.override.dispose(),this.removeClass("lm-mod-dragging");let e=t.index,n=t.targetIndex;-1!==n&&e!==n&&(D.move(this._titles,e,n),this._adjustCurrentForMove(e,n),this._tabMoved.emit({fromIndex:e,toIndex:n,title:this._titles[n]}),B.sendMessage(this,pe.Msg.UpdateRequest))}),n)}_releaseMouse(){let e=this._dragData;e&&(this._dragData=null,this.document.removeEventListener("pointermove",this,!0),this.document.removeEventListener("pointerup",this,!0),this.document.removeEventListener("keydown",this,!0),this.document.removeEventListener("contextmenu",this,!0),e.dragAborted=!0,e.dragActive&&(ze.resetTabPositions(this.contentNode.children,this._orientation),e.override.dispose(),e.tab.classList.remove("lm-mod-dragging"),this.removeClass("lm-mod-dragging")))}_adjustCurrentForInsert(e,t){let n=this.currentTitle,i=this._currentIndex,s=this.insertBehavior;if("select-tab"===s||"select-tab-if-needed"===s&&-1===i)return this._currentIndex=e,this._previousTitle=n,void this._currentChanged.emit({previousIndex:i,previousTitle:n,currentIndex:e,currentTitle:t});i>=e&&this._currentIndex++}_adjustCurrentForMove(e,t){this._currentIndex===e?this._currentIndex=t:this._currentIndex=t?this._currentIndex++:this._currentIndex>e&&this._currentIndex<=t&&this._currentIndex--}_adjustCurrentForRemove(e,t){let n=this._currentIndex,i=this.removeBehavior;if(n===e){if(0===this._titles.length)return this._currentIndex=-1,void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null});if("select-tab-after"===i)return this._currentIndex=Math.min(e,this._titles.length-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});if("select-tab-before"===i)return this._currentIndex=Math.max(0,e-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});if("select-previous-tab"===i)return this._previousTitle?(this._currentIndex=this._titles.indexOf(this._previousTitle),this._previousTitle=null):this._currentIndex=Math.min(e,this._titles.length-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});this._currentIndex=-1,this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null})}else n>e&&this._currentIndex--}_onTitleChanged(e){this.update()}}var ze,Ue,qe,We,He,Ke,$e,Ve,Je,Ge,Ye,Xe;!function(e){class t{constructor(){this.closeIconSelector=".lm-TabBar-tabCloseIcon",this._tabID=0,this._tabKeys=new WeakMap,this._uuid=++t._nInstance}renderTab(e){let t=e.title.caption,n=this.createTabKey(e),i=n,s=this.createTabStyle(e),r=this.createTabClass(e),o=this.createTabDataset(e),a=this.createTabARIA(e);return e.title.closable?ue.li({id:i,key:n,className:r,title:t,style:s,dataset:o,...a},this.renderIcon(e),this.renderLabel(e),this.renderCloseIcon(e)):ue.li({id:i,key:n,className:r,title:t,style:s,dataset:o,...a},this.renderIcon(e),this.renderLabel(e))}renderIcon(e){const{title:t}=e;let n=this.createIconClass(e);return ue.div({className:n},t.icon,t.iconLabel)}renderLabel(e){return ue.div({className:"lm-TabBar-tabLabel"},e.title.label)}renderCloseIcon(e){return ue.div({className:"lm-TabBar-tabCloseIcon"})}createTabKey(e){let t=this._tabKeys.get(e.title);return void 0===t&&(t=`tab-key-${this._uuid}-${this._tabID++}`,this._tabKeys.set(e.title,t)),t}createTabStyle(e){return{zIndex:`${e.zIndex}`}}createTabClass(e){let t="lm-TabBar-tab";return e.title.className&&(t+=` ${e.title.className}`),e.title.closable&&(t+=" lm-mod-closable"),e.current&&(t+=" lm-mod-current"),t}createTabDataset(e){return e.title.dataset}createTabARIA(e){var t;return{role:"tab","aria-selected":e.current.toString(),tabindex:`${null!==(t=e.tabIndex)&&void 0!==t?t:"-1"}`}}createIconClass(e){let t="lm-TabBar-tabIcon",n=e.title.iconClass;return n?`${t} ${n}`:t}}t._nInstance=0,e.Renderer=t,e.defaultRenderer=new t,e.addButtonSelector=".lm-TabBar-addButton"}(Ne||(Ne={})),function(e){e.DRAG_THRESHOLD=5,e.DETACH_THRESHOLD=20,e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");t.setAttribute("role","tablist"),t.className="lm-TabBar-content",e.appendChild(t);let n=document.createElement("div");return n.className="lm-TabBar-addButton lm-mod-hidden",n.setAttribute("tabindex","-1"),n.setAttribute("role","button"),e.appendChild(n),e},e.asTitle=function(e){return e instanceof he?e:new he(e)},e.parseTransitionDuration=function(e){let t=window.getComputedStyle(e);return 1e3*(parseFloat(t.transitionDuration)||0)},e.snapTabLayout=function(e,t){let n=new Array(e.length);for(let i=0,s=e.length;i=e.DRAG_THRESHOLD||s>=e.DRAG_THRESHOLD},e.detachExceeded=function(t,n){let i=t.contentRect;return n.clientX=i.right+e.DETACH_THRESHOLD||n.clientY=i.bottom+e.DETACH_THRESHOLD},e.layoutTabs=function(e,t,n,i){let s,r,o,a;"horizontal"===i?(s=t.pressX,r=n.clientX-t.contentRect.left,o=n.clientX,a=t.contentRect.width):(s=t.pressY,r=n.clientY-t.contentRect.top,o=n.clientY,a=t.contentRect.height);let l=t.index,c=r-t.tabPressPos,u=c+t.tabSize;for(let n=0,r=e.length;n>1);if(nt.index&&u>h)r=-t.tabSize-d.margin+"px",l=Math.max(l,n);else if(n===t.index){let e=o-s,n=a-(t.tabPos+t.tabSize);r=`${Math.max(-t.tabPos,Math.min(e,n))}px`}else r="";"horizontal"===i?e[n].style.left=r:e[n].style.top=r}t.targetIndex=l},e.finalizeTabPosition=function(e,t){let n,i;if(n="horizontal"===t?e.contentRect.width:e.contentRect.height,e.targetIndex===e.index)i=0;else if(e.targetIndex>e.index){let t=e.tabLayout[e.targetIndex];i=t.pos+t.size-e.tabSize-e.tabPos}else i=e.tabLayout[e.targetIndex].pos-e.tabPos;let s=n-(e.tabPos+e.tabSize),r=Math.max(-e.tabPos,Math.min(i,s));"horizontal"===t?e.tab.style.left=`${r}px`:e.tab.style.top=`${r}px`},e.resetTabPositions=function(e,t){for(const n of e)"horizontal"===t?n.style.left="":n.style.top=""}}(ze||(ze={}));class Ze extends fe{constructor(e){super(),this._spacing=4,this._dirty=!1,this._root=null,this._box=null,this._items=new Map,this.renderer=e.renderer,void 0!==e.spacing&&(this._spacing=Ae.clampDimension(e.spacing)),this._document=e.document||document,this._hiddenMode=void 0!==e.hiddenMode?e.hiddenMode:pe.HiddenMode.Display}dispose(){let e=this[Symbol.iterator]();this._items.forEach((e=>{e.dispose()})),this._box=null,this._root=null,this._items.clear();for(const t of e)t.dispose();super.dispose()}get hiddenMode(){return this._hiddenMode}set hiddenMode(e){if(this._hiddenMode!==e){this._hiddenMode=e;for(const e of this.tabBars())if(e.titles.length>1)for(const t of e.titles)t.owner.hiddenMode=this._hiddenMode}}get spacing(){return this._spacing}set spacing(e){e=Ae.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}get isEmpty(){return null===this._root}[Symbol.iterator](){return this._root?this._root.iterAllWidgets():S()}widgets(){return this._root?this._root.iterUserWidgets():S()}selectedWidgets(){return this._root?this._root.iterSelectedWidgets():S()}tabBars(){return this._root?this._root.iterTabBars():S()}handles(){return this._root?this._root.iterHandles():S()}moveHandle(e,t,n){let i=e.classList.contains("lm-mod-hidden");if(!this._root||i)return;let s,r=this._root.findSplitNode(e);r&&(s="horizontal"===r.node.orientation?t-e.offsetLeft:n-e.offsetTop,0!==s&&(r.node.holdSizes(),ie.adjust(r.node.sizers,r.index,s),this.parent&&this.parent.update()))}saveLayout(){return this._root?(this._root.holdAllSizes(),{main:this._root.createConfig()}):{main:null}}restoreLayout(e){let t,n=new Set;t=e.main?Ue.normalizeAreaConfig(e.main,n):null;let i=this.widgets(),s=this.tabBars(),r=this.handles();this._root=null;for(const e of i)n.has(e)||(e.parent=null);for(const e of s)e.dispose();for(const e of r)e.parentNode&&e.parentNode.removeChild(e);for(const e of n)e.parent=this.parent;this._root=t?Ue.realizeAreaConfig(t,{createTabBar:e=>this._createTabBar(),createHandle:()=>this._createHandle()},this._document):null,this.parent&&(n.forEach((e=>{this.attachWidget(e)})),this.parent.fit())}addWidget(e,t={}){let n=t.ref||null,i=t.mode||"tab-after",s=null;if(this._root&&n&&(s=this._root.findTabNode(n)),n&&!s)throw new Error("Reference widget is not in the layout.");switch(e.parent=this.parent,i){case"tab-after":this._insertTab(e,n,s,!0);break;case"tab-before":this._insertTab(e,n,s,!1);break;case"split-top":this._insertSplit(e,n,s,"vertical",!1);break;case"split-left":this._insertSplit(e,n,s,"horizontal",!1);break;case"split-right":this._insertSplit(e,n,s,"horizontal",!0);break;case"split-bottom":this._insertSplit(e,n,s,"vertical",!0);break;case"merge-top":this._insertSplit(e,n,s,"vertical",!1,!0);break;case"merge-left":this._insertSplit(e,n,s,"horizontal",!1,!0);break;case"merge-right":this._insertSplit(e,n,s,"horizontal",!0,!0);break;case"merge-bottom":this._insertSplit(e,n,s,"vertical",!0,!0)}this.parent&&(this.attachWidget(e),this.parent.fit())}removeWidget(e){this._removeWidget(e),this.parent&&(this.detachWidget(e),this.parent.fit())}hitTestTabAreas(e,t){if(!this._root||!this.parent||!this.parent.isVisible)return null;this._box||(this._box=M.boxSizing(this.parent.node));let n=this.parent.node.getBoundingClientRect(),i=e-n.left-this._box.borderLeft,s=t-n.top-this._box.borderTop,r=this._root.hitTestTabNodes(i,s);if(!r)return null;let{tabBar:o,top:a,left:l,width:c,height:u}=r,d=this._box.borderLeft+this._box.borderRight,h=this._box.borderTop+this._box.borderBottom;return{tabBar:o,x:i,y:s,top:a,left:l,right:n.width-d-(l+c),bottom:n.height-h-(a+u),width:c,height:u}}init(){super.init();for(const e of this)this.attachWidget(e);for(const e of this.handles())this.parent.node.appendChild(e);this.parent.fit()}attachWidget(e){this.parent.node!==e.node.parentNode&&(this._items.set(e,new me(e)),this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeAttach),this.parent.node.appendChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterAttach))}detachWidget(e){if(this.parent.node!==e.node.parentNode)return;this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeDetach),this.parent.node.removeChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterDetach);let t=this._items.get(e);t&&(this._items.delete(e),t.dispose())}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_removeWidget(e){if(!this._root)return;let t=this._root.findTabNode(e);if(!t)return;if(Ue.removeAria(e),t.tabBar.titles.length>1)return t.tabBar.removeTab(e.title),void(this._hiddenMode===pe.HiddenMode.Scale&&1==t.tabBar.titles.length&&(t.tabBar.titles[0].owner.hiddenMode=pe.HiddenMode.Display));if(t.tabBar.dispose(),this._root===t)return void(this._root=null);this._root.holdAllSizes();let n=t.parent;t.parent=null;let i=D.removeFirstOf(n.children,t),s=D.removeAt(n.handles,i);if(D.removeAt(n.sizers,i),s.parentNode&&s.parentNode.removeChild(s),n.children.length>1)return void n.syncHandles();let r=n.parent;n.parent=null;let o=n.children[0],a=n.handles[0];if(n.children.length=0,n.handles.length=0,n.sizers.length=0,a.parentNode&&a.parentNode.removeChild(a),this._root===n)return o.parent=null,void(this._root=o);let l=r,c=l.children.indexOf(n);if(o instanceof Ue.TabLayoutNode)return o.parent=l,void(l.children[c]=o);let u=D.removeAt(l.handles,c);D.removeAt(l.children,c),D.removeAt(l.sizers,c),u.parentNode&&u.parentNode.removeChild(u);for(let e=0,t=o.children.length;e=n.length)&&(i=0),{type:"tab-area",widgets:n,currentIndex:i}}(t,n):function(t,n){let i=t.orientation,s=[],r=[];for(let o=0,a=t.children.length;o{let l=s(i,n,r),c=t(e.sizes[a]),u=n.createHandle();o.children.push(l),o.handles.push(u),o.sizers.push(c),l.parent=o})),o.syncHandles(),o.normalizeSizes(),o}(r,o,a),l};class n{constructor(e){this.parent=null,this._top=0,this._left=0,this._width=0,this._height=0;let t=new de,n=new de;t.stretch=0,n.stretch=1,this.tabBar=e,this.sizers=[t,n]}get top(){return this._top}get left(){return this._left}get width(){return this._width}get height(){return this._height}*iterAllWidgets(){yield this.tabBar,yield*this.iterUserWidgets()}*iterUserWidgets(){for(const e of this.tabBar.titles)yield e.owner}*iterSelectedWidgets(){let e=this.tabBar.currentTitle;e&&(yield e.owner)}*iterTabBars(){yield this.tabBar}*iterHandles(){}findTabNode(e){return-1!==this.tabBar.titles.indexOf(e.title)?this:null}findSplitNode(e){return null}findFirstTabNode(){return this}hitTestTabNodes(e,t){return e=this._left+this._width||t=this._top+this._height?null:this}createConfig(){return{type:"tab-area",widgets:this.tabBar.titles.map((e=>e.owner)),currentIndex:this.tabBar.currentIndex}}holdAllSizes(){}fit(e,t){let n=0,i=0,s=t.get(this.tabBar),r=this.tabBar.currentTitle,o=r?t.get(r.owner):void 0,[a,l]=this.sizers;return s&&s.fit(),o&&o.fit(),s&&!s.isHidden?(n=Math.max(n,s.minWidth),i+=s.minHeight,a.minSize=s.minHeight,a.maxSize=s.maxHeight):(a.minSize=0,a.maxSize=0),o&&!o.isHidden?(n=Math.max(n,o.minWidth),i+=o.minHeight,l.minSize=o.minHeight,l.maxSize=1/0):(l.minSize=0,l.maxSize=1/0),{minWidth:n,minHeight:i,maxWidth:1/0,maxHeight:1/0}}update(e,t,n,i,s,r){this._top=t,this._left=e,this._width=n,this._height=i;let o=r.get(this.tabBar),a=this.tabBar.currentTitle,l=a?r.get(a.owner):void 0;if(ie.calc(this.sizers,i),o&&!o.isHidden){let i=this.sizers[0].size;o.update(e,t,n,i),t+=i}if(l&&!l.isHidden){let i=this.sizers[1].size;l.update(e,t,n,i)}}}e.TabLayoutNode=n;class i{constructor(e){this.parent=null,this.normalized=!1,this.children=[],this.sizers=[],this.handles=[],this.orientation=e}*iterAllWidgets(){for(const e of this.children)yield*e.iterAllWidgets()}*iterUserWidgets(){for(const e of this.children)yield*e.iterUserWidgets()}*iterSelectedWidgets(){for(const e of this.children)yield*e.iterSelectedWidgets()}*iterTabBars(){for(const e of this.children)yield*e.iterTabBars()}*iterHandles(){yield*this.handles;for(const e of this.children)yield*e.iterHandles()}findTabNode(e){for(let t=0,n=this.children.length;te.createConfig())),sizes:t}}syncHandles(){this.handles.forEach(((e,t)=>{e.setAttribute("data-orientation",this.orientation),t===this.handles.length-1?e.classList.add("lm-mod-hidden"):e.classList.remove("lm-mod-hidden")}))}holdSizes(){for(const e of this.sizers)e.sizeHint=e.size}holdAllSizes(){for(const e of this.children)e.holdAllSizes();this.holdSizes()}normalizeSizes(){let e=this.sizers.length;if(0===e)return;this.holdSizes();let t=this.sizers.reduce(((e,t)=>e+t.sizeHint),0);if(0===t)for(const t of this.sizers)t.size=t.sizeHint=1/e;else for(const e of this.sizers)e.size=e.sizeHint/=t;this.normalized=!0}createNormalizedSizes(){let e=this.sizers.length;if(0===e)return[];let t=this.sizers.map((e=>e.size)),n=t.reduce(((e,t)=>e+t),0);if(0===n)for(let n=t.length-1;n>-1;n--)t[n]=1/e;else for(let e=t.length-1;e>-1;e--)t[e]/=n;return t}fit(e,t){let n="horizontal"===this.orientation,i=Math.max(0,this.children.length-1)*e,s=n?i:0,r=n?0:i;for(let i=0,o=this.children.length;ithis._createTabBar(),createHandle:()=>this._createHandle()};this.layout=new Ze({document:this._document,renderer:t,spacing:e.spacing,hiddenMode:e.hiddenMode}),this.overlay=e.overlay||new Qe.Overlay,this.node.appendChild(this.overlay.node)}dispose(){this._releaseMouse(),this.overlay.hide(0),this._drag&&this._drag.dispose(),super.dispose()}get hiddenMode(){return this.layout.hiddenMode}set hiddenMode(e){this.layout.hiddenMode=e}get layoutModified(){return this._layoutModified}get addRequested(){return this._addRequested}get renderer(){return this.layout.renderer}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}get mode(){return this._mode}set mode(e){if(this._mode===e)return;this._mode=e,this.dataset.mode=e;let t=this.layout;switch(e){case"multiple-document":for(const e of t.tabBars())e.show();break;case"single-document":t.restoreLayout(qe.createSingleDocumentConfig(this));break;default:throw"unreachable"}B.postMessage(this,qe.LayoutModified)}get tabsMovable(){return this._tabsMovable}set tabsMovable(e){this._tabsMovable=e;for(const t of this.tabBars())t.tabsMovable=e}get tabsConstrained(){return this._tabsConstrained}set tabsConstrained(e){this._tabsConstrained=e}get addButtonEnabled(){return this._addButtonEnabled}set addButtonEnabled(e){this._addButtonEnabled=e;for(const t of this.tabBars())t.addButtonEnabled=e}get isEmpty(){return this.layout.isEmpty}*widgets(){yield*this.layout.widgets()}*selectedWidgets(){yield*this.layout.selectedWidgets()}*tabBars(){yield*this.layout.tabBars()}*handles(){yield*this.layout.handles()}selectWidget(e){let t=A(this.tabBars(),(t=>-1!==t.titles.indexOf(e.title)));if(!t)throw new Error("Widget is not contained in the dock panel.");t.currentTitle=e.title}activateWidget(e){this.selectWidget(e),e.activate()}saveLayout(){return this.layout.saveLayout()}restoreLayout(e){this._mode="multiple-document",this.layout.restoreLayout(e),(F.IS_EDGE||F.IS_IE)&&B.flush(),B.postMessage(this,qe.LayoutModified)}addWidget(e,t={}){"single-document"===this._mode?this.layout.addWidget(e):this.layout.addWidget(e,t),B.postMessage(this,qe.LayoutModified)}processMessage(e){"layout-modified"===e.type?this._layoutModified.emit(void 0):super.processMessage(e)}handleEvent(e){switch(e.type){case"lm-dragenter":this._evtDragEnter(e);break;case"lm-dragleave":this._evtDragLeave(e);break;case"lm-dragover":this._evtDragOver(e);break;case"lm-drop":this._evtDrop(e);break;case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("lm-dragenter",this),this.node.addEventListener("lm-dragleave",this),this.node.addEventListener("lm-dragover",this),this.node.addEventListener("lm-drop",this),this.node.addEventListener("pointerdown",this)}onAfterDetach(e){this.node.removeEventListener("lm-dragenter",this),this.node.removeEventListener("lm-dragleave",this),this.node.removeEventListener("lm-dragover",this),this.node.removeEventListener("lm-drop",this),this.node.removeEventListener("pointerdown",this),this._releaseMouse()}onChildAdded(e){qe.isGeneratedTabBarProperty.get(e.child)||e.child.addClass("lm-DockPanel-widget")}onChildRemoved(e){qe.isGeneratedTabBarProperty.get(e.child)||(e.child.removeClass("lm-DockPanel-widget"),B.postMessage(this,qe.LayoutModified))}_evtDragEnter(e){e.mimeData.hasData("application/vnd.lumino.widget-factory")&&(e.preventDefault(),e.stopPropagation())}_evtDragLeave(e){e.preventDefault(),this._tabsConstrained&&e.source!==this||(e.stopPropagation(),this.overlay.hide(1))}_evtDragOver(e){e.preventDefault(),this._tabsConstrained&&e.source!==this||"invalid"===this._showOverlay(e.clientX,e.clientY)?e.dropAction="none":(e.stopPropagation(),e.dropAction=e.proposedAction)}_evtDrop(e){if(e.preventDefault(),this.overlay.hide(0),"none"===e.proposedAction)return void(e.dropAction="none");let{clientX:t,clientY:n}=e,{zone:i,target:s}=qe.findDropTarget(this,t,n,this._edges);if(this._tabsConstrained&&e.source!==this||"invalid"===i)return void(e.dropAction="none");let r=e.mimeData.getData("application/vnd.lumino.widget-factory");if("function"!=typeof r)return void(e.dropAction="none");let o=r();if(!(o instanceof pe))return void(e.dropAction="none");if(o.contains(this))return void(e.dropAction="none");let a=s?qe.getDropRef(s.tabBar):null;switch(i){case"root-all":this.addWidget(o);break;case"root-top":this.addWidget(o,{mode:"split-top"});break;case"root-left":this.addWidget(o,{mode:"split-left"});break;case"root-right":this.addWidget(o,{mode:"split-right"});break;case"root-bottom":this.addWidget(o,{mode:"split-bottom"});break;case"widget-all":case"widget-tab":this.addWidget(o,{mode:"tab-after",ref:a});break;case"widget-top":this.addWidget(o,{mode:"split-top",ref:a});break;case"widget-left":this.addWidget(o,{mode:"split-left",ref:a});break;case"widget-right":this.addWidget(o,{mode:"split-right",ref:a});break;case"widget-bottom":this.addWidget(o,{mode:"split-bottom",ref:a});break;default:throw"unreachable"}e.dropAction=e.proposedAction,e.stopPropagation(),this.activateWidget(o)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation(),27===e.keyCode&&(this._releaseMouse(),B.postMessage(this,qe.LayoutModified))}_evtPointerDown(e){if(0!==e.button)return;let t=this.layout,n=e.target,i=A(t.handles(),(e=>e.contains(n)));if(!i)return;e.preventDefault(),e.stopPropagation(),this._document.addEventListener("keydown",this,!0),this._document.addEventListener("pointerup",this,!0),this._document.addEventListener("pointermove",this,!0),this._document.addEventListener("contextmenu",this,!0);let s=i.getBoundingClientRect(),r=e.clientX-s.left,o=e.clientY-s.top,a=window.getComputedStyle(i),l=G.overrideCursor(a.cursor,this._document);this._pressData={handle:i,deltaX:r,deltaY:o,override:l}}_evtPointerMove(e){if(!this._pressData)return;e.preventDefault(),e.stopPropagation();let t=this.node.getBoundingClientRect(),n=e.clientX-t.left-this._pressData.deltaX,i=e.clientY-t.top-this._pressData.deltaY;this.layout.moveHandle(this._pressData.handle,n,i)}_evtPointerUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this._releaseMouse(),B.postMessage(this,qe.LayoutModified))}_releaseMouse(){this._pressData&&(this._pressData.override.dispose(),this._pressData=null,this._document.removeEventListener("keydown",this,!0),this._document.removeEventListener("pointerup",this,!0),this._document.removeEventListener("pointermove",this,!0),this._document.removeEventListener("contextmenu",this,!0))}_showOverlay(e,t){let n,i,s,r,{zone:o,target:a}=qe.findDropTarget(this,e,t,this._edges);if("invalid"===o)return this.overlay.hide(100),o;let l=M.boxSizing(this.node),c=this.node.getBoundingClientRect();switch(o){case"root-all":n=l.paddingTop,i=l.paddingLeft,s=l.paddingRight,r=l.paddingBottom;break;case"root-top":n=l.paddingTop,i=l.paddingLeft,s=l.paddingRight,r=c.height*qe.GOLDEN_RATIO;break;case"root-left":n=l.paddingTop,i=l.paddingLeft,s=c.width*qe.GOLDEN_RATIO,r=l.paddingBottom;break;case"root-right":n=l.paddingTop,i=c.width*qe.GOLDEN_RATIO,s=l.paddingRight,r=l.paddingBottom;break;case"root-bottom":n=c.height*qe.GOLDEN_RATIO,i=l.paddingLeft,s=l.paddingRight,r=l.paddingBottom;break;case"widget-all":n=a.top,i=a.left,s=a.right,r=a.bottom;break;case"widget-top":n=a.top,i=a.left,s=a.right,r=a.bottom+a.height/2;break;case"widget-left":n=a.top,i=a.left,s=a.right+a.width/2,r=a.bottom;break;case"widget-right":n=a.top,i=a.left+a.width/2,s=a.right,r=a.bottom;break;case"widget-bottom":n=a.top+a.height/2,i=a.left,s=a.right,r=a.bottom;break;case"widget-tab":{const e=a.tabBar.node.getBoundingClientRect().height;n=a.top,i=a.left,s=a.right,r=a.bottom+a.height-e;break}default:throw"unreachable"}return this.overlay.show({top:n,left:i,right:s,bottom:r}),o}_createTabBar(){let e=this._renderer.createTabBar(this._document);return qe.isGeneratedTabBarProperty.set(e,!0),"single-document"===this._mode&&e.hide(),e.tabsMovable=this._tabsMovable,e.allowDeselect=!1,e.addButtonEnabled=this._addButtonEnabled,e.removeBehavior="select-previous-tab",e.insertBehavior="select-tab-if-needed",e.tabMoved.connect(this._onTabMoved,this),e.currentChanged.connect(this._onCurrentChanged,this),e.tabCloseRequested.connect(this._onTabCloseRequested,this),e.tabDetachRequested.connect(this._onTabDetachRequested,this),e.tabActivateRequested.connect(this._onTabActivateRequested,this),e.addRequested.connect(this._onTabAddRequested,this),e}_createHandle(){return this._renderer.createHandle()}_onTabMoved(){B.postMessage(this,qe.LayoutModified)}_onCurrentChanged(e,t){let{previousTitle:n,currentTitle:i}=t;n&&n.owner.hide(),i&&i.owner.show(),(F.IS_EDGE||F.IS_IE)&&B.flush(),B.postMessage(this,qe.LayoutModified)}_onTabAddRequested(e){this._addRequested.emit(e)}_onTabActivateRequested(e,t){t.title.owner.activate()}_onTabCloseRequested(e,t){t.title.owner.close()}_onTabDetachRequested(e,t){if(this._drag)return;e.releaseMouse();let{title:n,tab:i,clientX:s,clientY:r,offset:o}=t,a=new N.MimeData;a.setData("application/vnd.lumino.widget-factory",(()=>n.owner));let l=i.cloneNode(!0);o&&(l.style.top=`-${o.y}px`,l.style.left=`-${o.x}px`),this._drag=new G({document:this._document,mimeData:a,dragImage:l,proposedAction:"move",supportedActions:"move",source:this}),i.classList.add("lm-mod-hidden"),this._drag.start(s,r).then((()=>{this._drag=null,i.classList.remove("lm-mod-hidden")}))}}!function(e){e.Overlay=class{constructor(){this._timer=-1,this._hidden=!0,this.node=document.createElement("div"),this.node.classList.add("lm-DockPanel-overlay"),this.node.classList.add("lm-mod-hidden"),this.node.style.position="absolute",this.node.style.contain="strict"}show(e){let t=this.node.style;t.top=`${e.top}px`,t.left=`${e.left}px`,t.right=`${e.right}px`,t.bottom=`${e.bottom}px`,clearTimeout(this._timer),this._timer=-1,this._hidden&&(this._hidden=!1,this.node.classList.remove("lm-mod-hidden"))}hide(e){if(!this._hidden)return e<=0?(clearTimeout(this._timer),this._timer=-1,this._hidden=!0,void this.node.classList.add("lm-mod-hidden")):void(-1===this._timer&&(this._timer=window.setTimeout((()=>{this._timer=-1,this._hidden=!0,this.node.classList.add("lm-mod-hidden")}),e)))}};class t{createTabBar(e){let t=new Ne({document:e});return t.addClass("lm-DockPanel-tabBar"),t}createHandle(){let e=document.createElement("div");return e.className="lm-DockPanel-handle",e}}e.Renderer=t,e.defaultRenderer=new t}(Qe||(Qe={})),function(e){e.GOLDEN_RATIO=.618,e.DEFAULT_EDGES={top:12,right:40,bottom:40,left:40},e.LayoutModified=new q("layout-modified"),e.isGeneratedTabBarProperty=new W({name:"isGeneratedTabBar",create:()=>!1}),e.createSingleDocumentConfig=function(e){if(e.isEmpty)return{main:null};let t=Array.from(e.widgets()),n=e.selectedWidgets().next().value,i=n?t.indexOf(n):-1;return{main:{type:"tab-area",widgets:t,currentIndex:i}}},e.findDropTarget=function(e,t,n,i){if(!M.hitTest(e.node,t,n))return{zone:"invalid",target:null};let s=e.layout;if(s.isEmpty)return{zone:"root-all",target:null};if("multiple-document"===e.mode){let s=e.node.getBoundingClientRect(),r=t-s.left+1,o=n-s.top+1,a=s.right-t,l=s.bottom-n;switch(Math.min(o,a,l,r)){case o:if(od&&l>d&&a>h&&c>h)return{zone:"widget-all",target:r};switch(o/=d,a/=h,l/=d,c/=h,Math.min(o,a,l,c)){case o:u="widget-left";break;case a:u="widget-top";break;case l:u="widget-right";break;case c:u="widget-bottom";break;default:throw"unreachable"}return{zone:u,target:r}},e.getDropRef=function(e){return 0===e.titles.length?null:e.currentTitle?e.currentTitle.owner:e.titles[e.titles.length-1].owner}}(qe||(qe={}));class et extends fe{constructor(e={}){super(e),this._dirty=!1,this._rowSpacing=4,this._columnSpacing=4,this._items=[],this._rowStarts=[],this._columnStarts=[],this._rowSizers=[new de],this._columnSizers=[new de],this._box=null,void 0!==e.rowCount&&We.reallocSizers(this._rowSizers,e.rowCount),void 0!==e.columnCount&&We.reallocSizers(this._columnSizers,e.columnCount),void 0!==e.rowSpacing&&(this._rowSpacing=We.clampValue(e.rowSpacing)),void 0!==e.columnSpacing&&(this._columnSpacing=We.clampValue(e.columnSpacing))}dispose(){for(const e of this._items){let t=e.widget;e.dispose(),t.dispose()}this._box=null,this._items.length=0,this._rowStarts.length=0,this._rowSizers.length=0,this._columnStarts.length=0,this._columnSizers.length=0,super.dispose()}get rowCount(){return this._rowSizers.length}set rowCount(e){e!==this.rowCount&&(We.reallocSizers(this._rowSizers,e),this.parent&&this.parent.fit())}get columnCount(){return this._columnSizers.length}set columnCount(e){e!==this.columnCount&&(We.reallocSizers(this._columnSizers,e),this.parent&&this.parent.fit())}get rowSpacing(){return this._rowSpacing}set rowSpacing(e){e=We.clampValue(e),this._rowSpacing!==e&&(this._rowSpacing=e,this.parent&&this.parent.fit())}get columnSpacing(){return this._columnSpacing}set columnSpacing(e){e=We.clampValue(e),this._columnSpacing!==e&&(this._columnSpacing=e,this.parent&&this.parent.fit())}rowStretch(e){let t=this._rowSizers[e];return t?t.stretch:-1}setRowStretch(e,t){let n=this._rowSizers[e];n&&(t=We.clampValue(t),n.stretch!==t&&(n.stretch=t,this.parent&&this.parent.update()))}columnStretch(e){let t=this._columnSizers[e];return t?t.stretch:-1}setColumnStretch(e,t){let n=this._columnSizers[e];n&&(t=We.clampValue(t),n.stretch!==t&&(n.stretch=t,this.parent&&this.parent.update()))}*[Symbol.iterator](){for(const e of this._items)yield e.widget}addWidget(e){-1===D.findFirstIndex(this._items,(t=>t.widget===e))&&(this._items.push(new me(e)),this.parent&&this.attachWidget(e))}removeWidget(e){let t=D.findFirstIndex(this._items,(t=>t.widget===e));if(-1===t)return;let n=D.removeAt(this._items,t);this.parent&&this.detachWidget(e),n.dispose()}init(){super.init();for(const e of this)this.attachWidget(e)}attachWidget(e){this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeAttach),this.parent.node.appendChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterAttach),this.parent.fit()}detachWidget(e){this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeDetach),this.parent.node.removeChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterDetach),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){for(let e=0,t=this.rowCount;e!e.isHidden));for(let t=0,n=e.length;t({row:0,column:0,rowSpan:1,columnSpan:1}),changed:function(e){e.parent&&e.parent.layout instanceof et&&e.parent.fit()}}),e.normalizeConfig=function(e){return{row:Math.max(0,Math.floor(e.row||0)),column:Math.max(0,Math.floor(e.column||0)),rowSpan:Math.max(1,Math.floor(e.rowSpan||0)),columnSpan:Math.max(1,Math.floor(e.columnSpan||0))}},e.clampValue=function(e){return Math.max(0,Math.floor(e))},e.rowSpanCmp=function(t,n){let i=e.cellConfigProperty.get(t.widget),s=e.cellConfigProperty.get(n.widget);return i.rowSpan-s.rowSpan},e.columnSpanCmp=function(t,n){let i=e.cellConfigProperty.get(t.widget),s=e.cellConfigProperty.get(n.widget);return i.columnSpan-s.columnSpan},e.reallocSizers=function(e,t){for(t=Math.max(1,Math.floor(t));e.lengtht&&(e.length=t)},e.distributeMin=function(e,t,n,i){if(n=i)return;let r=(i-s)/(n-t+1);for(let i=t;i<=n;++i)e[i].minSize+=r}}(We||(We={}));class tt extends pe{constructor(e={}){super({node:He.createNode()}),this._activeIndex=-1,this._tabFocusIndex=0,this._menus=[],this._childMenu=null,this._overflowMenu=null,this._menuItemSizes=[],this._overflowIndex=-1,this.addClass("lm-MenuBar"),this.setFlag(pe.Flag.DisallowLayout),this.renderer=e.renderer||tt.defaultRenderer,this._forceItemsPosition=e.forceItemsPosition||{forceX:!0,forceY:!0},this._overflowMenuOptions=e.overflowMenuOptions||{isVisible:!0}}dispose(){this._closeChildMenu(),this._menus.length=0,super.dispose()}get childMenu(){return this._childMenu}get overflowIndex(){return this._overflowIndex}get overflowMenu(){return this._overflowMenu}get contentNode(){return this.node.getElementsByClassName("lm-MenuBar-content")[0]}get activeMenu(){return this._menus[this._activeIndex]||null}set activeMenu(e){this.activeIndex=e?this._menus.indexOf(e):-1}get activeIndex(){return this._activeIndex}set activeIndex(e){(e<0||e>=this._menus.length)&&(e=-1),e>-1&&0===this._menus[e].items.length&&(e=-1),this._activeIndex!==e&&(this._activeIndex=e,this.update())}get menus(){return this._menus}openActiveMenu(){-1!==this._activeIndex&&(this._openChildMenu(),this._childMenu&&(this._childMenu.activeIndex=-1,this._childMenu.activateNextItem()))}addMenu(e,t=!0){this.insertMenu(this._menus.length,e,t)}insertMenu(e,t,n=!0){this._closeChildMenu();let i=this._menus.indexOf(t),s=Math.max(0,Math.min(e,this._menus.length));if(-1===i)return D.insert(this._menus,s,t),t.addClass("lm-MenuBar-menu"),t.aboutToClose.connect(this._onMenuAboutToClose,this),t.menuRequested.connect(this._onMenuMenuRequested,this),t.title.changed.connect(this._onTitleChanged,this),void(n&&this.update());s===this._menus.length&&s--,i!==s&&(D.move(this._menus,i,s),n&&this.update())}removeMenu(e,t=!0){this.removeMenuAt(this._menus.indexOf(e),t)}removeMenuAt(e,t=!0){this._closeChildMenu();let n=D.removeAt(this._menus,e);n&&(n.aboutToClose.disconnect(this._onMenuAboutToClose,this),n.menuRequested.disconnect(this._onMenuMenuRequested,this),n.title.changed.disconnect(this._onTitleChanged,this),n.removeClass("lm-MenuBar-menu"),t&&this.update())}clearMenus(){if(0!==this._menus.length){this._closeChildMenu();for(let e of this._menus)e.aboutToClose.disconnect(this._onMenuAboutToClose,this),e.menuRequested.disconnect(this._onMenuMenuRequested,this),e.title.changed.disconnect(this._onTitleChanged,this),e.removeClass("lm-MenuBar-menu");this._menus.length=0,this.update()}}handleEvent(e){switch(e.type){case"keydown":this._evtKeyDown(e);break;case"mousedown":this._evtMouseDown(e);break;case"mousemove":this._evtMouseMove(e);break;case"focusout":this._evtFocusOut(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("keydown",this),this.node.addEventListener("mousedown",this),this.node.addEventListener("mousemove",this),this.node.addEventListener("focusout",this),this.node.addEventListener("contextmenu",this)}onAfterDetach(e){this.node.removeEventListener("keydown",this),this.node.removeEventListener("mousedown",this),this.node.removeEventListener("mousemove",this),this.node.removeEventListener("focusout",this),this.node.removeEventListener("contextmenu",this),this._closeChildMenu()}onActivateRequest(e){this.isAttached&&this._focusItemAt(0)}onResize(e){this.update(),super.onResize(e)}onUpdateRequest(e){var t;let n=this._menus,i=this.renderer,s=this._activeIndex,r=this._tabFocusIndex>=0&&this._tabFocusIndex-1?this._overflowIndex:n.length,a=0,l=!1;o=null!==this._overflowMenu?o-1:o;let c=new Array(o);for(let e=0;e{this._tabFocusIndex=e,this.activeIndex=e}}),a+=this._menuItemSizes[e],n[e].title.label===this._overflowMenuOptions.title&&(l=!0,o--);if(this._overflowMenuOptions.isVisible)if(this._overflowIndex>-1&&!l){if(null===this._overflowMenu){const e=null!==(t=this._overflowMenuOptions.title)&&void 0!==t?t:"...";this._overflowMenu=new Te({commands:new ae}),this._overflowMenu.title.label=e,this._overflowMenu.title.mnemonic=0,this.addMenu(this._overflowMenu,!1)}for(let e=n.length-2;e>=o;e--){const t=this.menus[e];t.title.mnemonic=0,this._overflowMenu.insertItem(0,{type:"submenu",submenu:t}),this.removeMenu(t,!1)}c[o]=i.renderItem({title:this._overflowMenu.title,active:o===s&&0!==n[o].items.length,tabbable:o===r,disabled:0===n[o].items.length,onfocus:()=>{this._tabFocusIndex=o,this.activeIndex=o}}),o++}else if(null!==this._overflowMenu){let e=this._overflowMenu.items,t=this.node.offsetWidth,s=this._overflowMenu.items.length;for(let l=0;lthis._menuItemSizes[s]){let t=e[0].submenu;this._overflowMenu.removeItemAt(0),this.insertMenu(o,t,!1),c[o]=i.renderItem({title:t.title,active:!1,tabbable:o===r,disabled:0===n[o].items.length,onfocus:()=>{this._tabFocusIndex=o,this.activeIndex=o}}),o++}}0===this._overflowMenu.items.length&&(this.removeMenu(this._overflowMenu,!1),c.pop(),this._overflowMenu=null,this._overflowIndex=-1)}te.render(c,this.contentNode),this._updateOverflowIndex()}_updateOverflowIndex(){if(!this._overflowMenuOptions.isVisible)return;const e=this.contentNode.childNodes;let t=this.node.offsetWidth,n=0,i=-1,s=e.length;if(0==this._menuItemSizes.length)for(let r=0;rt&&-1===i&&(i=r)}else for(let e=0;et){i=e;break}this._overflowIndex=i}_evtKeyDown(e){let t=e.keyCode;if(9===t)return void(this.activeIndex=-1);if(e.preventDefault(),e.stopPropagation(),13===t||32===t||38===t||40===t){if(this.activeIndex=this._tabFocusIndex,this.activeIndex!==this._tabFocusIndex)return;return void this.openActiveMenu()}if(27===t)return this._closeChildMenu(),void this._focusItemAt(this.activeIndex);if(37===t||39===t){let e=37===t?-1:1,n=this._tabFocusIndex+e,i=this._menus.length;for(let t=0;tM.hitTest(t,e.clientX,e.clientY)));if(-1!==t){if(0===e.button)if(this._childMenu)this._closeChildMenu(),this.activeIndex=t;else{e.preventDefault();const n=this._positionForMenu(t);Te.saveWindowData(),this.activeIndex=t,this._openChildMenu(n)}}else this._closeChildMenu()}_evtMouseMove(e){let t=D.findFirstIndex(this.contentNode.children,(t=>M.hitTest(t,e.clientX,e.clientY)));if(t===this._activeIndex)return;if(-1===t&&this._childMenu)return;const n=t>=0&&this._childMenu?this._positionForMenu(t):null;Te.saveWindowData(),this.activeIndex=t,n&&this._openChildMenu(n)}_positionForMenu(e){let t=this.contentNode.children[e],{left:n,bottom:i}=t.getBoundingClientRect();return{top:i,left:n}}_evtFocusOut(e){this._childMenu||this.node.contains(e.relatedTarget)||(this.activeIndex=-1)}_focusItemAt(e){const t=this.contentNode.childNodes[e];t&&t.focus()}_openChildMenu(e={}){let t=this.activeMenu;if(!t)return void this._closeChildMenu();let n=this._childMenu;if(n===t)return;this._childMenu=t,n?n.close():document.addEventListener("mousedown",this,!0),this._tabFocusIndex=this.activeIndex,B.sendMessage(this,pe.Msg.UpdateRequest);let{left:i,top:s}=e;void 0!==i&&void 0!==s||({left:i,top:s}=this._positionForMenu(this._activeIndex)),n||this.addClass("lm-mod-active"),t.items.length>0&&t.open(i,s,this._forceItemsPosition)}_closeChildMenu(){if(!this._childMenu)return;this.removeClass("lm-mod-active"),document.removeEventListener("mousedown",this,!0);let e=this._childMenu;this._childMenu=null,e.close(),this.activeIndex=-1}_onMenuAboutToClose(e){e===this._childMenu&&(this.removeClass("lm-mod-active"),document.removeEventListener("mousedown",this,!0),this._childMenu=null,this.activeIndex=-1)}_onMenuMenuRequested(e,t){if(e!==this._childMenu)return;let n=this._activeIndex,i=this._menus.length;switch(t){case"next":this.activeIndex=n===i-1?0:n+1;break;case"previous":this.activeIndex=0===n?i-1:n-1}this.openActiveMenu()}_onTitleChanged(){this.update()}}!function(e){class t{renderItem(e){let t=this.createItemClass(e),n=this.createItemDataset(e),i=this.createItemARIA(e);return ue.li({className:t,dataset:n,...e.disabled?{}:{tabindex:e.tabbable?"0":"-1"},onfocus:e.onfocus,...i},this.renderIcon(e),this.renderLabel(e))}renderIcon(e){let t=this.createIconClass(e);return ue.div({className:t},e.title.icon,e.title.iconLabel)}renderLabel(e){let t=this.formatLabel(e);return ue.div({className:"lm-MenuBar-itemLabel"},t)}createItemClass(e){let t="lm-MenuBar-item";return e.title.className&&(t+=` ${e.title.className}`),e.active&&!e.disabled&&(t+=" lm-mod-active"),t}createItemDataset(e){return e.title.dataset}createItemARIA(e){return{role:"menuitem","aria-haspopup":"true","aria-disabled":e.disabled?"true":"false"}}createIconClass(e){let t="lm-MenuBar-itemIcon",n=e.title.iconClass;return n?`${t} ${n}`:t}formatLabel(e){let{label:t,mnemonic:n}=e.title;if(n<0||n>=t.length)return t;let i=t.slice(0,n),s=t.slice(n+1),r=t[n];return[i,ue.span({className:"lm-MenuBar-itemMnemonic"},r),s]}}e.Renderer=t,e.defaultRenderer=new t}(tt||(tt={})),function(e){e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");return t.className="lm-MenuBar-content",e.appendChild(t),t.setAttribute("role","menubar"),e},e.findMnemonic=function(e,t,n){let i=-1,s=-1,r=!1,o=t.toUpperCase();for(let t=0,a=e.length;t=0&&u1&&this.widgets.forEach((e=>{e.hiddenMode=this._hiddenMode})))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,super.dispose()}attachWidget(e,t){this._hiddenMode===pe.HiddenMode.Scale&&this._items.length>0?(1===this._items.length&&(this.widgets[0].hiddenMode=pe.HiddenMode.Scale),t.hiddenMode=pe.HiddenMode.Scale):t.hiddenMode=pe.HiddenMode.Display,D.insert(this._items,e,new me(t)),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){D.move(this._items,e,t),this.parent.update()}detachWidget(e,t){let n=D.removeAt(this._items,e);this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach),n.widget.node.style.zIndex="",this._hiddenMode===pe.HiddenMode.Scale&&(t.hiddenMode=pe.HiddenMode.Display,1===this._items.length&&(this._items[0].widget.hiddenMode=pe.HiddenMode.Display)),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){let e=0,t=0;for(let n=0,i=this._items.length;n=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(Je||(Je={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(Ye||(Ye={}));class st{constructor(e){this._delegate=new h.PromiseDelegate,this._plugins=new Map,this._services=new Map,this._started=!1,this._bubblingKeydown=!1,this.commands=new E,this.contextMenu=new Le({commands:this.commands,renderer:e.contextMenuRenderer}),this.shell=e.shell}get started(){return this._delegate.promise}getPluginDescription(e){var t,n;return null!==(n=null===(t=this._plugins.get(e))||void 0===t?void 0:t.description)&&void 0!==n?n:""}hasPlugin(e){return this._plugins.has(e)}isPluginActivated(e){var t,n;return null!==(n=null===(t=this._plugins.get(e))||void 0===t?void 0:t.activated)&&void 0!==n&&n}listPlugins(){return Array.from(this._plugins.keys())}registerPlugin(e){if(this._plugins.has(e.id))throw new TypeError(`Plugin '${e.id}' is already registered.`);const t=Xe.createPluginData(e);Xe.ensureNoCycle(t,this._plugins,this._services),t.provides&&this._services.set(t.provides,t.id),this._plugins.set(t.id,t)}registerPlugins(e){for(const t of e)this.registerPlugin(t)}deregisterPlugin(e,t){const n=this._plugins.get(e);if(n){if(n.activated&&!t)throw new Error(`Plugin '${e}' is still active.`);this._plugins.delete(e)}}async activatePlugin(e){const t=this._plugins.get(e);if(!t)throw new ReferenceError(`Plugin '${e}' is not registered.`);if(t.activated)return;if(t.promise)return t.promise;const n=t.requires.map((e=>this.resolveRequiredService(e))),i=t.optional.map((e=>this.resolveOptionalService(e)));return t.promise=Promise.all([...n,...i]).then((e=>t.activate.apply(void 0,[this,...e]))).then((e=>{t.service=e,t.activated=!0,t.promise=null})).catch((e=>{throw t.promise=null,e})),t.promise}async deactivatePlugin(e){const t=this._plugins.get(e);if(!t)throw new ReferenceError(`Plugin '${e}' is not registered.`);if(!t.activated)return[];if(!t.deactivate)throw new TypeError(`Plugin '${e}'#deactivate() method missing`);const n=Xe.findDependents(e,this._plugins,this._services),i=n.map((e=>this._plugins.get(e)));for(const t of i)if(!t.deactivate)throw new TypeError(`Plugin ${t.id}#deactivate() method missing (depends on ${e})`);for(const e of i){const t=[...e.requires,...e.optional].map((e=>{const t=this._services.get(e);return t?this._plugins.get(t).service:null}));await e.deactivate(this,...t),e.service=null,e.activated=!1}return n.pop(),n}async resolveRequiredService(e){const t=this._services.get(e);if(!t)throw new TypeError(`No provider for: ${e.name}.`);const n=this._plugins.get(t);return n.activated||await this.activatePlugin(t),n.service}async resolveOptionalService(e){const t=this._services.get(e);if(!t)return null;const n=this._plugins.get(t);if(!n.activated)try{await this.activatePlugin(t)}catch(e){return console.error(e),null}return n.service}start(e={}){if(this._started)return this._delegate.promise;this._started=!0,this._bubblingKeydown=e.bubblingKeydown||!1;const t=e.hostID||"",n=Xe.collectStartupPlugins(this._plugins,e).map((e=>this.activatePlugin(e).catch((t=>{console.error(`Plugin '${e}' failed to activate.`),console.error(t)}))));return Promise.all(n).then((()=>{this.attachShell(t),this.addEventListeners(),this._delegate.resolve()})),this._delegate.promise}get deferredPlugins(){return Array.from(this._plugins).filter((([e,t])=>"defer"===t.autoStart)).map((([e,t])=>e))}async activateDeferredPlugins(){const e=this.deferredPlugins.filter((e=>this._plugins.get(e).autoStart)).map((e=>this.activatePlugin(e)));await Promise.all(e)}handleEvent(e){switch(e.type){case"resize":this.evtResize(e);break;case"keydown":this.evtKeydown(e);break;case"contextmenu":this.evtContextMenu(e)}}attachShell(e){pe.attach(this.shell,e&&document.getElementById(e)||document.body)}addEventListeners(){document.addEventListener("contextmenu",this),document.addEventListener("keydown",this,!this._bubblingKeydown),window.addEventListener("resize",this)}evtKeydown(e){this.commands.processKeydownEvent(e)}evtContextMenu(e){e.shiftKey||this.contextMenu.open(e)&&(e.preventDefault(),e.stopPropagation())}evtResize(e){this.shell.update()}}!function(e){e.createPluginData=function(e){var t,n,i,s;return{id:e.id,description:null!==(t=e.description)&&void 0!==t?t:"",service:null,promise:null,activated:!1,activate:e.activate,deactivate:null!==(n=e.deactivate)&&void 0!==n?n:null,provides:null!==(i=e.provides)&&void 0!==i?i:null,autoStart:null!==(s=e.autoStart)&&void 0!==s&&s,requires:e.requires?e.requires.slice():[],optional:e.optional?e.optional.slice():[]}},e.ensureNoCycle=function(e,t,n){const i=[...e.requires,...e.optional],s=i=>{if(i===e.provides)return!0;const o=n.get(i);if(!o)return!1;const a=t.get(o),l=[...a.requires,...a.optional];return 0!==l.length&&(r.push(o),!!l.some(s)||(r.pop(),!1))};if(!e.provides||0===i.length)return;const r=[e.id];if(i.some(s))throw new ReferenceError(`Cycle detected: ${r.join(" -> ")}.`)},e.findDependents=function(e,t,n){const i=new Array,s=e=>{const s=t.get(e),r=[...s.requires,...s.optional];i.push(...r.reduce(((t,i)=>{const s=n.get(i);return s&&t.push([e,s]),t}),[]))};for(const e of t.keys())s(e);const r=i.filter((t=>t[1]===e));let o=0;for(;r.length>o;){const e=r.length,t=new Set(r.map((e=>e[0])));for(const e of t)i.filter((t=>t[1]===e)).forEach((e=>{r.includes(e)||r.push(e)}));o=e}const a=function(e){let t=[],n=new Set,i=new Map;for(const t of e)s(t);for(const[e]of i)r(e);return t;function s(e){let[t,n]=e,s=i.get(n);s?s.push(t):i.set(n,[t])}function r(e){if(n.has(e))return;n.add(e);let s=i.get(e);if(s)for(const e of s)r(e);t.push(e)}}(r),l=a.findIndex((t=>t===e));return-1===l?[e]:a.slice(0,l+1)},e.collectStartupPlugins=function(e,t){const n=new Set;for(const t of e.keys())!0===e.get(t).autoStart&&n.add(t);if(t.startPlugins)for(const e of t.startPlugins)n.add(e);if(t.ignorePlugins)for(const e of t.ignorePlugins)n.delete(e);return Array.from(n)}}(Xe||(Xe={}));var rt=n(9988);class ot{constructor(){this._routes=[]}get(e,t){this._add("GET",e,t)}put(e,t){this._add("PUT",e,t)}post(e,t){this._add("POST",e,t)}patch(e,t){this._add("PATCH",e,t)}delete(e,t){this._add("DELETE",e,t)}async route(e){const t=new URL(e.url),{method:n}=e,{pathname:i}=t;for(const s of this._routes){if(s.method!==n)continue;const r=i.match(s.pattern);if(!r)continue;const o=r.slice(1);let a;if("PATCH"===s.method||"PUT"===s.method||"POST"===s.method)try{a=JSON.parse(await e.text())}catch{a=void 0}return s.callback.call(null,{pathname:i,body:a,query:Object.fromEntries(t.searchParams)},...o)}throw new Error("Cannot route "+e.method+" "+e.url)}_add(e,t,n){"string"==typeof t&&(t=new RegExp(t)),this._routes.push({method:e,pattern:t,callback:n})}}class at{constructor(e){this._stream=new p.Stream(this),this._serverSettings=e.serverSettings}async emit(e){}dispose(){}get isDisposed(){return!0}get stream(){return this._stream}get serverSettings(){return this._serverSettings}}class lt extends st{constructor(e){var t;super(e),this.name="JupyterLite Server",this.namespace=this.name,this.version="unknown",this._router=new ot;const n={...u.ServerConnection.makeSettings(),WebSocket:rt.WebSocket,fetch:null!==(t=this.fetch.bind(this))&&void 0!==t?t:void 0};this._serviceManager=new u.ServiceManager({standby:"never",serverSettings:n,events:new at({serverSettings:n})})}get router(){return this._router}get serviceManager(){return this._serviceManager}async fetch(e,t){if(!(e instanceof Request))throw Error("Request info is not a Request");return this._router.route(e)}attachShell(e){}evtResize(e){}registerPluginModule(e){let t=e.default;Object.prototype.hasOwnProperty.call(e,"__esModule")||(t=e),Array.isArray(t)||(t=[t]),t.forEach((e=>{try{this.registerPlugin(e)}catch(e){console.error(e)}}))}registerPluginModules(e){e.forEach((e=>{this.registerPluginModule(e)}))}}var ct=n(1729),ut=n(3570)},3570:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var i=n(5082),s=n(4016),r=n(9622),o=n(1729);class a{constructor(e){var t;this._registration=null,this._registrationChanged=new s.Signal(this),this._ready=new i.PromiseDelegate;const n=null!==(t=null==e?void 0:e.workerUrl)&&void 0!==t?t:r.URLExt.join(r.PageConfig.getBaseUrl(),o.o);this.initialize(n).catch(console.warn)}get registrationChanged(){return this._registrationChanged}get enabled(){return null!==this._registration}get ready(){return this._ready.promise}async initialize(e){const{serviceWorker:t}=navigator;let n=null;if(t?t.controller&&(n=await t.getRegistration(t.controller.scriptURL)||null,console.info("JupyterLite ServiceWorker was already registered")):console.warn("ServiceWorkers not supported in this browser"),!n&&t)try{console.info("Registering new JupyterLite ServiceWorker",e),n=await t.register(e),console.info("JupyterLite ServiceWorker was sucessfully registered")}catch(e){console.warn(e),console.warn(`JupyterLite ServiceWorker registration unexpectedly failed: ${e}`)}this.setRegistration(n),n?this._ready.resolve(void 0):this._ready.reject(void 0)}setRegistration(e){this._registration=e,this._registrationChanged.emit(this._registration)}}},3744:()=>{"use strict";const e="precache",t=new BroadcastChannel("/api/drive.v1");async function n(){return await caches.open(e)}async function i(e,t){return(await n()).put(e,t)}self.addEventListener("install",(function(e){self.skipWaiting(),e.waitUntil(async function(){const e=await n();return await e.addAll([])}())})),self.addEventListener("activate",(function(e){e.waitUntil(self.clients.claim())})),self.addEventListener("fetch",(async function(e){const{request:s}=e,r=new URL(e.request.url);let o=null;!function(e){return e.origin===location.origin&&e.pathname.includes("/api/drive")}(r)?function(e,t){return"GET"!==e.method||null===t.origin.match(/^http/)||t.pathname.includes("/api/")}(s,r)||(o=async function(e){const{request:t}=e;let s=await async function(e){const t=await n(),i=await t.match(e);return i&&404!==i.status?i:null}(t);return s?e.waitUntil(async function(e){const t=await fetch(e);return await i(e,t),t}(t)):(s=await fetch(t),e.waitUntil(i(t,s.clone()))),s}(e)):o=async function(e){const n=new Promise((e=>{t.onmessage=t=>{e(new Response(JSON.stringify(t.data)))}})),i=await e.json();return i.receiver="broadcast.ts",t.postMessage(i),await n}(s),o&&e.respondWith(o)}))},1729:(e,t,n)=>{"use strict";n.d(t,{f:()=>o,o:()=>a});var i=n(5082),s=n(3744),r=n.n(s);const o=new i.Token("@jupyterlite/server-extension:IServiceWorkerManager"),a=`${r()}`.split("/").slice(-1)[0]},5259:(e,t,n)=>{"use strict";var i,s,r;function o(e,t){let n=0;for(const i of e)if(t(i,n++))return i}n.d(t,{RO:()=>i,sE:()=>o}),function(e){function t(e,t,n=0,i=-1){let s,r=e.length;if(0===r)return-1;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(i||(i={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(r||(r={}))},5082:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},4016:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Signal:()=>o,Stream:()=>a});var i,s=n(5259),r=n(5082);class o{constructor(e){this.sender=e}connect(e,t){return i.connect(this,e,t)}disconnect(e,t){return i.disconnect(this,e,t)}emit(e){i.emit(this,e)}}!function(e){e.disconnectBetween=function(e,t){i.disconnectBetween(e,t)},e.disconnectSender=function(e){i.disconnectSender(e)},e.disconnectReceiver=function(e){i.disconnectReceiver(e)},e.disconnectAll=function(e){i.disconnectAll(e)},e.clearData=function(e){i.disconnectAll(e)},e.getExceptionHandler=function(){return i.exceptionHandler},e.setExceptionHandler=function(e){let t=i.exceptionHandler;return i.exceptionHandler=e,t}}(o||(o={}));class a extends o{constructor(){super(...arguments),this._pending=new r.PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new r.PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new r.PromiseDelegate}}!function(e){function t(e){let t=i.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,u(r.get(t))}u(t)}}function n(e){let t=r.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,u(i.get(t))}u(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let s=i.get(e.sender);if(s||(s=[],i.set(e.sender,s)),l(s,e,t,n))return!1;let o=n||t,a=r.get(o);a||(a=[],r.set(o,a));let c={signal:e,slot:t,thisArg:n};return s.push(c),a.push(c),!0},e.disconnect=function(e,t,n){n=n||void 0;let s=i.get(e.sender);if(!s||0===s.length)return!1;let o=l(s,e,t,n);if(!o)return!1;let a=n||t,c=r.get(a);return o.signal=null,u(s),u(c),!0},e.disconnectBetween=function(e,t){let n=i.get(e);if(!n||0===n.length)return;let s=r.get(t);if(s&&0!==s.length){for(const t of s)t.signal&&t.signal.sender===e&&(t.signal=null);u(n),u(s)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=i.get(e.sender);if(n&&0!==n.length)for(let i=0,s=n.length;ie.signal===t&&e.slot===n&&e.thisArg===i))}function c(t,n){let{signal:i,slot:s,thisArg:r}=t;try{s.call(r,i.sender,n)}catch(t){e.exceptionHandler(t)}}function u(e){0===o.size&&a(d),o.add(e)}function d(){o.forEach(h),o.clear()}function h(e){s.RO.removeAllWhere(e,p)}function p(e){return null===e.signal}}(i||(i={}))},9146:e=>{"use strict";function t(){this._types=Object.create(null),this._extensions=Object.create(null);for(let e=0;e{"use strict";let i=n(9146);e.exports=new i(n(4415),n(3014))},3014:e=>{e.exports={"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}},4415:e=>{e.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}},1173:e=>{e.exports={}}},__webpack_module_cache__={},leafPrototypes,getProto,inProgress,dataWebpackPrefix;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.m=__webpack_modules__,__webpack_require__.amdO={},__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var n=Object.create(null);__webpack_require__.r(n);var i={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;"object"==typeof s&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach((t=>i[t]=()=>e[t]));return i.default=()=>e,__webpack_require__.d(n,i),n},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce(((t,n)=>(__webpack_require__.f[n](e,t),t)),[])),__webpack_require__.u=e=>e+".thebe-lite.min.js",__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),inProgress={},dataWebpackPrefix="thebe-lite:",__webpack_require__.l=(e,t,n,i)=>{if(inProgress[e])inProgress[e].push(t);else{var s,r;if(void 0!==n)for(var o=document.getElementsByTagName("script"),a=0;a{s.onerror=s.onload=null,clearTimeout(u);var i=inProgress[e];if(delete inProgress[e],s.parentNode&&s.parentNode.removeChild(s),i&&i.forEach((e=>e(n))),t)return t(n)},u=setTimeout(c.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=c.bind(null,s.onerror),s.onload=c.bind(null,s.onload),r&&document.head.appendChild(s)}},__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})(),(()=>{__webpack_require__.b=document.baseURI||self.location.href;var e={143:0};__webpack_require__.f.j=(t,n)=>{var i=__webpack_require__.o(e,t)?e[t]:void 0;if(0!==i)if(i)n.push(i[2]);else{var s=new Promise(((n,s)=>i=e[t]=[n,s]));n.push(i[2]=s);var r=__webpack_require__.p+__webpack_require__.u(t),o=new Error;__webpack_require__.l(r,(n=>{if(__webpack_require__.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=n&&("load"===n.type?"missing":n.type),r=n&&n.target&&n.target.src;o.message="Loading chunk "+t+" failed.\n("+s+": "+r+")",o.name="ChunkLoadError",o.type=s,o.request=r,i[1](o)}}),"chunk-"+t,t)}};var t=(t,n)=>{var i,s,[r,o,a]=n,l=0;if(r.some((t=>0!==e[t]))){for(i in o)__webpack_require__.o(o,i)&&(__webpack_require__.m[i]=o[i]);a&&a(__webpack_require__)}for(t&&t(n);l{var __webpack_modules__={2918:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseManager=void 0;const i=n(544),s=n(2700);t.BaseManager=class{constructor(e){var t;this._isDisposed=!1,this._disposed=new i.Signal(this),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings()}get disposed(){return this._disposed}get isDisposed(){return this._isDisposed}get isActive(){return!0}dispose(){this.isDisposed||(this._disposed.emit(void 0),i.Signal.clearData(this))}}},1611:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BuildManager=void 0;const i=n(8920),s=n(2700);t.BuildManager=class{constructor(e={}){var t;this._url="",this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings();const{baseUrl:n,appUrl:r}=this.serverSettings;this._url=i.URLExt.join(n,r,"api/build")}get isAvailable(){return"true"===i.PageConfig.getOption("buildAvailable").toLowerCase()}get shouldCheck(){return"true"===i.PageConfig.getOption("buildCheck").toLowerCase()}getStatus(){const{_url:e,serverSettings:t}=this;return s.ServerConnection.makeRequest(e,{},t).then((e=>{if(200!==e.status)throw new s.ServerConnection.ResponseError(e);return e.json()})).then((e=>{if("string"!=typeof e.status)throw new Error("Invalid data");if("string"!=typeof e.message)throw new Error("Invalid data");return e}))}build(){const{_url:e,serverSettings:t}=this;return s.ServerConnection.makeRequest(e,{method:"POST"},t).then((e=>{if(400===e.status)throw new s.ServerConnection.ResponseError(e,"Build aborted");if(200!==e.status){const t=`Build failed with ${e.status}.\n\n If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').\n\n If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;throw new s.ServerConnection.ResponseError(e,t)}}))}cancel(){const{_url:e,serverSettings:t}=this;return s.ServerConnection.makeRequest(e,{method:"DELETE"},t).then((e=>{if(204!==e.status)throw new s.ServerConnection.ResponseError(e)}))}}},2677:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ConfigWithDefaults=t.ConfigSection=void 0;const i=n(8920),s=n(6914);(t.ConfigSection||(t.ConfigSection={})).create=function(e){const t=new r(e);return t.load().then((()=>t))};class r{constructor(e){var t;this._url="unknown";const n=this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings();this._url=i.URLExt.join(n.baseUrl,"api/config",encodeURIComponent(e.name))}get data(){return this._data}async load(){const e=await s.ServerConnection.makeRequest(this._url,{},this.serverSettings);if(200!==e.status)throw await s.ServerConnection.ResponseError.create(e);this._data=await e.json()}async update(e){this._data={...this._data,...e};const t={method:"PATCH",body:JSON.stringify(e)},n=await s.ServerConnection.makeRequest(this._url,t,this.serverSettings);if(200!==n.status)throw await s.ServerConnection.ResponseError.create(n);return this._data=await n.json(),this._data}}t.ConfigWithDefaults=class{constructor(e){var t,n;this._className="",this._section=e.section,this._defaults=null!==(t=e.defaults)&&void 0!==t?t:{},this._className=null!==(n=e.className)&&void 0!==n?n:""}get(e){const t=this._classData();return e in t?t[e]:this._defaults[e]}set(e,t){const n={};if(n[e]=t,this._className){const e={};return e[this._className]=n,this._section.update(e)}return this._section.update(n)}_classData(){const e=this._section.data;return this._className&&this._className in e?e[this._className]:e}}},7593:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Drive=t.ContentsManager=t.Contents=void 0;const o=n(8920),a=n(544),l=n(6914),c=r(n(7033));var u,d;(d=t.Contents||(t.Contents={})).validateContentsModel=function(e){c.validateContentsModel(e)},d.validateCheckpointModel=function(e){c.validateCheckpointModel(e)},t.ContentsManager=class{constructor(e={}){var t,n;this._isDisposed=!1,this._additionalDrives=new Map,this._fileChanged=new a.Signal(this);const i=this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:l.ServerConnection.makeSettings();this._defaultDrive=null!==(n=e.defaultDrive)&&void 0!==n?n:new h({serverSettings:i}),this._defaultDrive.fileChanged.connect(this._onFileChanged,this)}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,a.Signal.clearData(this))}addDrive(e){this._additionalDrives.set(e.name,e),e.fileChanged.connect(this._onFileChanged,this)}getSharedModelFactory(e){var t;const[n]=this._driveForPath(e);return null!==(t=null==n?void 0:n.sharedModelFactory)&&void 0!==t?t:null}localPath(e){const t=e.split("/"),n=t[0].split(":");return 1!==n.length&&this._additionalDrives.has(n[0])?o.PathExt.join(n.slice(1).join(":"),...t.slice(1)):o.PathExt.removeSlash(e)}normalize(e){const t=e.split(":");return 1===t.length?o.PathExt.normalize(e):`${t[0]}:${o.PathExt.normalize(t.slice(1).join(":"))}`}resolvePath(e,t){const n=this.driveName(e),i=this.localPath(e),s=o.PathExt.resolve("/",i,t);return n?`${n}:${s}`:s}driveName(e){const t=e.split("/")[0].split(":");return 1===t.length?"":this._additionalDrives.has(t[0])?t[0]:""}get(e,t){const[n,i]=this._driveForPath(e);return n.get(i,t).then((e=>{const t=[];if("directory"===e.type&&e.content){for(const i of e.content)t.push({...i,path:this._toGlobalPath(n,i.path)});return{...e,path:this._toGlobalPath(n,i),content:t,serverPath:e.path}}return{...e,path:this._toGlobalPath(n,i),serverPath:e.path}}))}getDownloadUrl(e){const[t,n]=this._driveForPath(e);return t.getDownloadUrl(n)}newUntitled(e={}){if(e.path){const t=this.normalize(e.path),[n,i]=this._driveForPath(t);return n.newUntitled({...e,path:i}).then((e=>({...e,path:o.PathExt.join(t,e.name),serverPath:e.path})))}return this._defaultDrive.newUntitled(e)}delete(e){const[t,n]=this._driveForPath(e);return t.delete(n)}rename(e,t){const[n,i]=this._driveForPath(e),[s,r]=this._driveForPath(t);if(n!==s)throw Error("ContentsManager: renaming files must occur within a Drive");return n.rename(i,r).then((e=>({...e,path:this._toGlobalPath(n,r),serverPath:e.path})))}save(e,t={}){const n=this.normalize(e),[i,s]=this._driveForPath(e);return i.save(s,{...t,path:s}).then((e=>({...e,path:n,serverPath:e.path})))}copy(e,t){const[n,i]=this._driveForPath(e),[s,r]=this._driveForPath(t);if(n===s)return n.copy(i,r).then((e=>({...e,path:this._toGlobalPath(n,e.path),serverPath:e.path})));throw Error("Copying files between drives is not currently implemented")}createCheckpoint(e){const[t,n]=this._driveForPath(e);return t.createCheckpoint(n)}listCheckpoints(e){const[t,n]=this._driveForPath(e);return t.listCheckpoints(n)}restoreCheckpoint(e,t){const[n,i]=this._driveForPath(e);return n.restoreCheckpoint(i,t)}deleteCheckpoint(e,t){const[n,i]=this._driveForPath(e);return n.deleteCheckpoint(i,t)}_toGlobalPath(e,t){return e===this._defaultDrive?o.PathExt.removeSlash(t):`${e.name}:${o.PathExt.removeSlash(t)}`}_driveForPath(e){const t=this.driveName(e),n=this.localPath(e);return t?[this._additionalDrives.get(t),n]:[this._defaultDrive,n]}_onFileChanged(e,t){var n,i;if(e===this._defaultDrive)this._fileChanged.emit(t);else{let s=null,r=null;(null===(n=t.newValue)||void 0===n?void 0:n.path)&&(s={...t.newValue,path:this._toGlobalPath(e,t.newValue.path)}),(null===(i=t.oldValue)||void 0===i?void 0:i.path)&&(r={...t.oldValue,path:this._toGlobalPath(e,t.oldValue.path)}),this._fileChanged.emit({type:t.type,newValue:s,oldValue:r})}}};class h{constructor(e={}){var t,n,i;this._isDisposed=!1,this._fileChanged=new a.Signal(this),this.name=null!==(t=e.name)&&void 0!==t?t:"Default",this._apiEndpoint=null!==(n=e.apiEndpoint)&&void 0!==n?n:"api/contents",this.serverSettings=null!==(i=e.serverSettings)&&void 0!==i?i:l.ServerConnection.makeSettings()}get fileChanged(){return this._fileChanged}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,a.Signal.clearData(this))}async get(e,t){let n=this._getUrl(e);if(t){"notebook"===t.type&&delete t.format;const e=t.content?"1":"0",i={...t,content:e};n+=o.URLExt.objectToQueryString(i)}const i=this.serverSettings,s=await l.ServerConnection.makeRequest(n,{},i);if(200!==s.status)throw await l.ServerConnection.ResponseError.create(s);const r=await s.json();return c.validateContentsModel(r),r}getDownloadUrl(e){const t=this.serverSettings.baseUrl;let n=o.URLExt.join(t,"files",o.URLExt.encodeParts(e));const i=document.cookie.match("\\b_xsrf=([^;]*)\\b");if(i){const e=new URL(n);e.searchParams.append("_xsrf",i[1]),n=e.toString()}return Promise.resolve(n)}async newUntitled(e={}){var t;let n="{}";e&&(e.ext&&(e.ext=u.normalizeExtension(e.ext)),n=JSON.stringify(e));const i=this.serverSettings,s=this._getUrl(null!==(t=e.path)&&void 0!==t?t:""),r={method:"POST",body:n},o=await l.ServerConnection.makeRequest(s,r,i);if(201!==o.status)throw await l.ServerConnection.ResponseError.create(o);const a=await o.json();return c.validateContentsModel(a),this._fileChanged.emit({type:"new",oldValue:null,newValue:a}),a}async delete(e){const t=this._getUrl(e),n=this.serverSettings,i=await l.ServerConnection.makeRequest(t,{method:"DELETE"},n);if(204!==i.status)throw await l.ServerConnection.ResponseError.create(i);this._fileChanged.emit({type:"delete",oldValue:{path:e},newValue:null})}async rename(e,t){const n=this.serverSettings,i=this._getUrl(e),s={method:"PATCH",body:JSON.stringify({path:t})},r=await l.ServerConnection.makeRequest(i,s,n);if(200!==r.status)throw await l.ServerConnection.ResponseError.create(r);const o=await r.json();return c.validateContentsModel(o),this._fileChanged.emit({type:"rename",oldValue:{path:e},newValue:o}),o}async save(e,t={}){const n=this.serverSettings,i=this._getUrl(e),s={method:"PUT",body:JSON.stringify(t)},r=await l.ServerConnection.makeRequest(i,s,n);if(200!==r.status&&201!==r.status)throw await l.ServerConnection.ResponseError.create(r);const o=await r.json();return c.validateContentsModel(o),this._fileChanged.emit({type:"save",oldValue:null,newValue:o}),o}async copy(e,t){const n=this.serverSettings,i=this._getUrl(t),s={method:"POST",body:JSON.stringify({copy_from:e})},r=await l.ServerConnection.makeRequest(i,s,n);if(201!==r.status)throw await l.ServerConnection.ResponseError.create(r);const o=await r.json();return c.validateContentsModel(o),this._fileChanged.emit({type:"new",oldValue:null,newValue:o}),o}async createCheckpoint(e){const t=this._getUrl(e,"checkpoints"),n=await l.ServerConnection.makeRequest(t,{method:"POST"},this.serverSettings);if(201!==n.status)throw await l.ServerConnection.ResponseError.create(n);const i=await n.json();return c.validateCheckpointModel(i),i}async listCheckpoints(e){const t=this._getUrl(e,"checkpoints"),n=await l.ServerConnection.makeRequest(t,{},this.serverSettings);if(200!==n.status)throw await l.ServerConnection.ResponseError.create(n);const i=await n.json();if(!Array.isArray(i))throw new Error("Invalid Checkpoint list");for(let e=0;eo.URLExt.encodeParts(e))),n=this.serverSettings.baseUrl;return o.URLExt.join(n,this._apiEndpoint,...t)}}t.Drive=h,function(e){e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e}}(u||(u={}))},7033:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateCheckpointModel=t.validateContentsModel=void 0;const i=n(8193);t.validateContentsModel=function(e){(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"path","string"),(0,i.validateProperty)(e,"type","string"),(0,i.validateProperty)(e,"created","string"),(0,i.validateProperty)(e,"last_modified","string"),(0,i.validateProperty)(e,"mimetype","object"),(0,i.validateProperty)(e,"content","object"),(0,i.validateProperty)(e,"format","object")},t.validateCheckpointModel=function(e){(0,i.validateProperty)(e,"id","string"),(0,i.validateProperty)(e,"last_modified","string")}},3354:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventManager=void 0;const i=n(8920),s=n(9033),r=n(544),o=n(2700),a="api/events";t.EventManager=class{constructor(e={}){var t;this._socket=null,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:o.ServerConnection.makeSettings(),this._poll=new s.Poll({factory:()=>this._subscribe()}),this._stream=new r.Stream(this),this._poll.start()}get isDisposed(){return this._poll.isDisposed}get stream(){return this._stream}dispose(){if(this.isDisposed)return;this._poll.dispose();const e=this._socket;e&&(this._socket=null,e.onopen=()=>{},e.onerror=()=>{},e.onmessage=()=>{},e.onclose=()=>{},e.close()),r.Signal.clearData(this),this._stream.stop()}async emit(e){const{serverSettings:t}=this,{baseUrl:n,token:s}=t,{makeRequest:r,ResponseError:l}=o.ServerConnection,c=i.URLExt.join(n,a)+(s?`?token=${s}`:""),u={body:JSON.stringify(e),method:"POST"},d=await r(c,u,t);if(204!==d.status)throw new l(d)}_subscribe(){return new Promise(((e,t)=>{if(this.isDisposed)return;const{token:n,WebSocket:s,wsUrl:r}=this.serverSettings,o=i.URLExt.join(r,a,"subscribe")+(n?`?token=${encodeURIComponent(n)}`:""),l=this._socket=new s(o),c=this._stream;l.onclose=()=>t(new Error("EventManager socket closed")),l.onmessage=e=>e.data&&c.emit(JSON.parse(e.data))}))}}},6914:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(2918),t),s(n(2677),t),s(n(7593),t),s(n(3354),t),s(n(582),t),s(n(5312),t),s(n(8463),t),s(n(2700),t),s(n(7054),t),s(n(6052),t),s(n(8235),t),s(n(7523),t),s(n(87),t),s(n(4933),t)},5045:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CommHandler=void 0;const o=n(4643),a=r(n(1632));class l extends o.DisposableDelegate{constructor(e,t,n,i){super(i),this._target="",this._id="",this._id=t,this._target=e,this._kernel=n}get commId(){return this._id}get targetName(){return this._target}get onClose(){return this._onClose}set onClose(e){this._onClose=e}get onMsg(){return this._onMsg}set onMsg(e){this._onMsg=e}open(e,t,n=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot open");const i=a.createMessage({msgType:"comm_open",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,target_name:this._target,data:null!=e?e:{}},metadata:t,buffers:n});return this._kernel.sendShellMessage(i,!1,!0)}send(e,t,n=[],i=!0){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot send");const s=a.createMessage({msgType:"comm_msg",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:e},metadata:t,buffers:n});return this._kernel.sendShellMessage(s,!1,i)}close(e,t,n=[]){if(this.isDisposed||this._kernel.isDisposed)throw new Error("Cannot close");const i=a.createMessage({msgType:"comm_close",channel:"shell",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:null!=e?e:{}},metadata:t,buffers:n}),s=this._kernel.sendShellMessage(i,!1,!0),r=this._onClose;return r&&r(a.createMessage({msgType:"comm_close",channel:"iopub",username:this._kernel.username,session:this._kernel.clientId,content:{comm_id:this._id,data:null!=e?e:{}},metadata:t,buffers:n})),this.dispose(),s}}t.CommHandler=l},2094:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelConnection=void 0;const o=n(8920),a=n(5168),l=n(544),c=n(6914),u=n(5045),d=r(n(1632)),h=n(9178),p=n(7411),f=r(n(5537)),m=n(5312),g=r(n(925)),v="_RESTARTING_";class _{constructor(e){var t,n,i,s;this._createSocket=(e=!0)=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const t=this.serverSettings,n=o.URLExt.join(t.wsUrl,g.KERNEL_SERVICE_URL,encodeURIComponent(this._id)),i=n.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/,"$1");console.debug(`Starting WebSocket: ${i}`);let s=o.URLExt.join(n,"channels?session_id="+encodeURIComponent(this._clientId));const r=t.token;t.appendToken&&""!==r&&(s+=`&token=${encodeURIComponent(r)}`);const a=e?this._supportedProtocols:[];this._ws=new t.WebSocket(s,a),this._ws.binaryType="arraybuffer";let l=!1;const u=async e=>{var n,i;if(!this._isDisposed){this._reason="",this._model=void 0;try{const n=await g.getKernelModel(this._id,t);this._model=n,"dead"===(null==n?void 0:n.execution_state)?this._updateStatus("dead"):this._onWSClose(e)}catch(t){if(t instanceof c.ServerConnection.NetworkError||503===(null===(n=t.response)||void 0===n?void 0:n.status)||424===(null===(i=t.response)||void 0===i?void 0:i.status)){const t=1e3*y.getRandomIntInclusive(10,30);setTimeout(u,t,e)}else this._reason="Kernel died unexpectedly",this._updateStatus("dead")}}},d=async e=>{l||(l=!0,await u(e))};this._ws.onmessage=this._onWSMessage,this._ws.onopen=this._onWSOpen,this._ws.onclose=d,this._ws.onerror=d},this._onWSOpen=e=>{if(""!==this._ws.protocol&&!this._supportedProtocols.includes(this._ws.protocol))throw console.log("Server selected unknown kernel wire protocol:",this._ws.protocol),this._updateStatus("dead"),new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);this._selectedProtocol=this._ws.protocol,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose,this._updateConnectionStatus("connected")},this._onWSMessage=e=>{let t;try{t=(0,p.deserialize)(e.data,this._ws.protocol),f.validateMessage(t)}catch(e){throw e.message=`Kernel message validation error: ${e.message}`,e}this._kernelSession=t.header.session,this._msgChain=this._msgChain.then((()=>this._handleMessage(t))).catch((e=>{e.message.startsWith("Canceled future for ")&&console.error(e)})),this._anyMessage.emit({msg:t,direction:"recv"})},this._onWSClose=e=>{this.isDisposed||this._reconnect()},this._id="",this._name="",this._status="unknown",this._connectionStatus="connecting",this._kernelSession="",this._isDisposed=!1,this._ws=null,this._username="",this._reconnectLimit=7,this._reconnectAttempt=0,this._reconnectTimeout=null,this._supportedProtocols=Object.values(d.supportedKernelWebSocketProtocols),this._selectedProtocol="",this._futures=new Map,this._comms=new Map,this._targetRegistry=Object.create(null),this._info=new a.PromiseDelegate,this._pendingMessages=[],this._statusChanged=new l.Signal(this),this._connectionStatusChanged=new l.Signal(this),this._disposed=new l.Signal(this),this._iopubMessage=new l.Signal(this),this._anyMessage=new l.Signal(this),this._pendingInput=new l.Signal(this),this._unhandledMessage=new l.Signal(this),this._displayIdToParentIds=new Map,this._msgIdToDisplayIds=new Map,this._msgChain=Promise.resolve(),this._hasPendingInput=!1,this._reason="",this._noOp=()=>{},this._name=e.model.name,this._id=e.model.id,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:c.ServerConnection.makeSettings(),this._clientId=null!==(n=e.clientId)&&void 0!==n?n:a.UUID.uuid4(),this._username=null!==(i=e.username)&&void 0!==i?i:"",this.handleComms=null===(s=e.handleComms)||void 0===s||s,this._createSocket()}get disposed(){return this._disposed}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get model(){return this._model||{id:this.id,name:this.name,reason:this._reason}}get anyMessage(){return this._anyMessage}get pendingInput(){return this._pendingInput}get id(){return this._id}get name(){return this._name}get username(){return this._username}get clientId(){return this._clientId}get status(){return this._status}get connectionStatus(){return this._connectionStatus}get isDisposed(){return this._isDisposed}get info(){return this._info.promise}get spec(){return this._specPromise||(this._specPromise=m.KernelSpecAPI.getSpecs(this.serverSettings).then((e=>e.kernelspecs[this._name]))),this._specPromise}clone(e={}){return new _({model:this.model,username:this.username,serverSettings:this.serverSettings,handleComms:!1,...e})}dispose(){this.isDisposed||(this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearKernelState(),this._pendingMessages=[],this._clearSocket(),l.Signal.clearData(this))}sendShellMessage(e,t=!1,n=!0){return this._sendKernelShellControl(h.KernelShellFutureHandler,e,t,n)}sendControlMessage(e,t=!1,n=!0){return this._sendKernelShellControl(h.KernelControlFutureHandler,e,t,n)}_sendKernelShellControl(e,t,n=!1,i=!0){this._sendMessage(t),this._anyMessage.emit({msg:t,direction:"send"});const s=new e((()=>{const e=t.header.msg_id;this._futures.delete(e);const n=this._msgIdToDisplayIds.get(e);n&&(n.forEach((t=>{const n=this._displayIdToParentIds.get(t);if(n){const i=n.indexOf(e);if(-1===i)return;1===n.length?this._displayIdToParentIds.delete(t):(n.splice(i,1),this._displayIdToParentIds.set(t,n))}})),this._msgIdToDisplayIds.delete(e))}),t,n,i,this);return this._futures.set(t.header.msg_id,s),s}_sendMessage(e,t=!0){if("dead"===this.status)throw new Error("Kernel is dead");if((""===this._kernelSession||this._kernelSession===v)&&d.isInfoRequestMsg(e)){if("connected"===this.connectionStatus)return void this._ws.send((0,p.serialize)(e,this._ws.protocol));throw new Error("Could not send message: status is not connected")}if(t&&this._pendingMessages.length>0)this._pendingMessages.push(e);else if("connected"===this.connectionStatus&&this._kernelSession!==v)this._ws.send((0,p.serialize)(e,this._ws.protocol));else{if(!t)throw new Error("Could not send message");this._pendingMessages.push(e)}}async interrupt(){if(this.hasPendingInput=!1,"dead"===this.status)throw new Error("Kernel is dead");return g.interruptKernel(this.id,this.serverSettings)}async restart(){if("dead"===this.status)throw new Error("Kernel is dead");this._updateStatus("restarting"),this._clearKernelState(),this._kernelSession=v,await g.restartKernel(this.id,this.serverSettings),await this.reconnect(),this.hasPendingInput=!1}reconnect(){this._errorIfDisposed();const e=new a.PromiseDelegate,t=(n,i)=>{"connected"===i?(e.resolve(),this.connectionStatusChanged.disconnect(t,this)):"disconnected"===i&&(e.reject(new Error("Kernel connection disconnected")),this.connectionStatusChanged.disconnect(t,this))};return this.connectionStatusChanged.connect(t,this),this._reconnectAttempt=0,this._reconnect(),e.promise}async shutdown(){"dead"!==this.status&&await g.shutdownKernel(this.id,this.serverSettings),this.handleShutdown()}handleShutdown(){this._updateStatus("dead"),this.dispose()}async requestKernelInfo(){const e=d.createMessage({msgType:"kernel_info_request",channel:"shell",username:this._username,session:this._clientId,content:{}});let t;try{t=await y.handleShellMessage(this,e)}catch(e){if(this.isDisposed)return;throw e}if(this._errorIfDisposed(),t)return void 0===t.content.status&&(t.content.status="ok"),"ok"!==t.content.status?(this._info.reject("Kernel info reply errored"),t):(this._info.resolve(t.content),this._kernelSession=t.header.session,t)}requestComplete(e){const t=d.createMessage({msgType:"complete_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestInspect(e){const t=d.createMessage({msgType:"inspect_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestHistory(e){const t=d.createMessage({msgType:"history_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestExecute(e,t=!0,n){const i=d.createMessage({msgType:"execute_request",channel:"shell",username:this._username,session:this._clientId,content:{silent:!1,store_history:!0,user_expressions:{},allow_stdin:!0,stop_on_error:!1,...e},metadata:n});return this.sendShellMessage(i,!0,t)}requestDebug(e,t=!0){const n=d.createMessage({msgType:"debug_request",channel:"control",username:this._username,session:this._clientId,content:e});return this.sendControlMessage(n,!0,t)}requestIsComplete(e){const t=d.createMessage({msgType:"is_complete_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}requestCommInfo(e){const t=d.createMessage({msgType:"comm_info_request",channel:"shell",username:this._username,session:this._clientId,content:e});return y.handleShellMessage(this,t)}sendInputReply(e,t){const n=d.createMessage({msgType:"input_reply",channel:"stdin",username:this._username,session:this._clientId,content:e});n.parent_header=t,this._sendMessage(n),this._anyMessage.emit({msg:n,direction:"send"}),this.hasPendingInput=!1}createComm(e,t=a.UUID.uuid4()){if(!this.handleComms)throw new Error("Comms are disabled on this kernel connection");if(this._comms.has(t))throw new Error("Comm is already created");const n=new u.CommHandler(e,t,this,(()=>{this._unregisterComm(t)}));return this._comms.set(t,n),n}hasComm(e){return this._comms.has(e)}registerCommTarget(e,t){this.handleComms&&(this._targetRegistry[e]=t)}removeCommTarget(e,t){this.handleComms&&(this.isDisposed||this._targetRegistry[e]!==t||delete this._targetRegistry[e])}registerMessageHook(e,t){var n;const i=null===(n=this._futures)||void 0===n?void 0:n.get(e);i&&i.registerMessageHook(t)}removeMessageHook(e,t){var n;const i=null===(n=this._futures)||void 0===n?void 0:n.get(e);i&&i.removeMessageHook(t)}removeInputGuard(){this.hasPendingInput=!1}async _handleDisplayId(e,t){var n,i;const s=t.parent_header.msg_id;let r=this._displayIdToParentIds.get(e);if(r){const e={header:a.JSONExt.deepCopy(t.header),parent_header:a.JSONExt.deepCopy(t.parent_header),metadata:a.JSONExt.deepCopy(t.metadata),content:a.JSONExt.deepCopy(t.content),channel:t.channel,buffers:t.buffers?t.buffers.slice():[]};e.header.msg_type="update_display_data",await Promise.all(r.map((async t=>{const n=this._futures&&this._futures.get(t);n&&await n.handleMsg(e)})))}if("update_display_data"===t.header.msg_type)return!0;r=null!==(n=this._displayIdToParentIds.get(e))&&void 0!==n?n:[],-1===r.indexOf(s)&&r.push(s),this._displayIdToParentIds.set(e,r);const o=null!==(i=this._msgIdToDisplayIds.get(s))&&void 0!==i?i:[];return-1===o.indexOf(s)&&o.push(s),this._msgIdToDisplayIds.set(s,o),!1}_clearSocket(){null!==this._ws&&(this._ws.onopen=this._noOp,this._ws.onclose=this._noOp,this._ws.onerror=this._noOp,this._ws.onmessage=this._noOp,this._ws.close(),this._ws=null)}_updateStatus(e){this._status!==e&&"dead"!==this._status&&(this._status=e,y.logKernelStatus(this),this._statusChanged.emit(e),"dead"===e&&this.dispose())}_sendPending(){for(;"connected"===this.connectionStatus&&this._kernelSession!==v&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}_clearKernelState(){this._kernelSession="",this._pendingMessages=[],this._futures.forEach((e=>{e.dispose()})),this._comms.forEach((e=>{e.dispose()})),this._msgChain=Promise.resolve(),this._futures=new Map,this._comms=new Map,this._displayIdToParentIds.clear(),this._msgIdToDisplayIds.clear()}_assertCurrentMessage(e){if(this._errorIfDisposed(),e.header.session!==this._kernelSession)throw new Error(`Canceling handling of old message: ${e.header.msg_type}`)}async _handleCommOpen(e){this._assertCurrentMessage(e);const t=e.content,n=new u.CommHandler(t.target_name,t.comm_id,this,(()=>{this._unregisterComm(t.comm_id)}));this._comms.set(t.comm_id,n);try{const i=await y.loadObject(t.target_name,t.target_module,this._targetRegistry);await i(n,e)}catch(e){throw n.close(),console.error("Exception opening new comm"),e}}async _handleCommClose(e){this._assertCurrentMessage(e);const t=e.content,n=this._comms.get(t.comm_id);if(!n)return void console.error("Comm not found for comm id "+t.comm_id);this._unregisterComm(n.commId);const i=n.onClose;i&&await i(e),n.dispose()}async _handleCommMsg(e){this._assertCurrentMessage(e);const t=e.content,n=this._comms.get(t.comm_id);if(!n)return;const i=n.onMsg;i&&await i(e)}_unregisterComm(e){this._comms.delete(e)}_updateConnectionStatus(e){if(this._connectionStatus!==e){if(this._connectionStatus=e,"connecting"!==e&&(this._reconnectAttempt=0,clearTimeout(this._reconnectTimeout)),"dead"!==this.status)if("connected"===e){let e=this._kernelSession===v,t=this.requestKernelInfo(),n=!1,i=()=>{n||(n=!0,e&&this._kernelSession===v&&(this._kernelSession=""),clearTimeout(s),this._pendingMessages.length>0&&this._sendPending())};t.then(i);let s=setTimeout(i,3e3)}else this._updateStatus("unknown");this._connectionStatusChanged.emit(e)}}async _handleMessage(e){var t,n;let i=!1;if(e.parent_header&&"iopub"===e.channel&&(d.isDisplayDataMsg(e)||d.isUpdateDisplayDataMsg(e)||d.isExecuteResultMsg(e))){const n=(null!==(t=e.content.transient)&&void 0!==t?t:{}).display_id;n&&(i=await this._handleDisplayId(n,e),this._assertCurrentMessage(e))}if(!i&&e.parent_header){const t=e.parent_header,i=null===(n=this._futures)||void 0===n?void 0:n.get(t.msg_id);if(i)await i.handleMsg(e),this._assertCurrentMessage(e);else{const n=t.session===this.clientId;"iopub"!==e.channel&&n&&this._unhandledMessage.emit(e)}}if("iopub"===e.channel){switch(e.header.msg_type){case"status":{const t=e.content.execution_state;"restarting"===t&&Promise.resolve().then((async()=>{this._updateStatus("autorestarting"),this._clearKernelState(),await this.reconnect()})),this._updateStatus(t);break}case"comm_open":this.handleComms&&await this._handleCommOpen(e);break;case"comm_msg":this.handleComms&&await this._handleCommMsg(e);break;case"comm_close":this.handleComms&&await this._handleCommClose(e)}this.isDisposed||(this._assertCurrentMessage(e),this._iopubMessage.emit(e))}}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt{if(t){if("undefined"==typeof requirejs)throw new Error("requirejs not found");requirejs([t],(n=>{void 0===n[e]?s(new Error(`Object '${e}' not found in module '${t}'`)):i(n[e])}),s)}else(null==n?void 0:n[e])?i(n[e]):s(new Error(`Object '${e}' not found in registry`))}))},e.getRandomIntInclusive=function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}}(y||(y={}))},9178:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelShellFutureHandler=t.KernelControlFutureHandler=t.KernelFutureHandler=void 0;const o=n(5168),a=n(4643),l=r(n(1632));class c extends a.DisposableDelegate{constructor(e,t,n,i,s){super(e),this._status=0,this._stdin=u.noOp,this._iopub=u.noOp,this._reply=u.noOp,this._done=new o.PromiseDelegate,this._hooks=new u.HookList,this._disposeOnDone=!0,this._msg=t,n||this._setFlag(u.KernelFutureFlag.GotReply),this._disposeOnDone=i,this._kernel=s}get msg(){return this._msg}get done(){return this._done.promise}get onReply(){return this._reply}set onReply(e){this._reply=e}get onIOPub(){return this._iopub}set onIOPub(e){this._iopub=e}get onStdin(){return this._stdin}set onStdin(e){this._stdin=e}registerMessageHook(e){if(this.isDisposed)throw new Error("Kernel future is disposed");this._hooks.add(e)}removeMessageHook(e){this.isDisposed||this._hooks.remove(e)}sendInputReply(e,t){this._kernel.sendInputReply(e,t)}dispose(){this._stdin=u.noOp,this._iopub=u.noOp,this._reply=u.noOp,this._hooks=null,this._testFlag(u.KernelFutureFlag.IsDone)||(this._done.promise.catch((()=>{})),this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`))),super.dispose()}async handleMsg(e){switch(e.channel){case"control":case"shell":e.channel===this.msg.channel&&e.parent_header.msg_id===this.msg.header.msg_id&&await this._handleReply(e);break;case"stdin":await this._handleStdin(e);break;case"iopub":await this._handleIOPub(e)}}async _handleReply(e){const t=this._reply;t&&await t(e),this._replyMsg=e,this._setFlag(u.KernelFutureFlag.GotReply),this._testFlag(u.KernelFutureFlag.GotIdle)&&this._handleDone()}async _handleStdin(e){this._kernel.hasPendingInput=!0;const t=this._stdin;t&&await t(e)}async _handleIOPub(e){const t=await this._hooks.process(e),n=this._iopub;t&&n&&await n(e),l.isStatusMsg(e)&&"idle"===e.content.execution_state&&(this._setFlag(u.KernelFutureFlag.GotIdle),this._testFlag(u.KernelFutureFlag.GotReply)&&this._handleDone())}_handleDone(){this._testFlag(u.KernelFutureFlag.IsDone)||(this._setFlag(u.KernelFutureFlag.IsDone),this._done.resolve(this._replyMsg),this._disposeOnDone&&this.dispose())}_testFlag(e){return 0!=(this._status&e)}_setFlag(e){this._status|=e}}var u;t.KernelFutureHandler=c,t.KernelControlFutureHandler=class extends c{},t.KernelShellFutureHandler=class extends c{},function(e){e.noOp=()=>{};const t="function"==typeof requestAnimationFrame?requestAnimationFrame:setImmediate;let n;e.HookList=class{constructor(){this._hooks=[]}add(e){this.remove(e),this._hooks.push(e)}remove(e){const t=this._hooks.indexOf(e);t>=0&&(this._hooks[t]=null,this._scheduleCompact())}async process(e){await this._processing;const t=new o.PromiseDelegate;let n;this._processing=t.promise;for(let i=this._hooks.length-1;i>=0;i--){const s=this._hooks[i];if(null!==s){try{n=await s(e)}catch(e){n=!0,console.error(e)}if(!1===n)return t.resolve(void 0),!1}}return t.resolve(void 0),!0}_scheduleCompact(){this._compactScheduled||(this._compactScheduled=!0,t((()=>{this._processing=this._processing.then((()=>{this._compactScheduled=!1,this._compact()}))})))}_compact(){let e=0;for(let t=0,n=this._hooks.length;t{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},2810:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.KernelManager=void 0;const i=n(9033),s=n(544),r=n(6914),o=n(2918),a=n(925),l=n(2094);class c extends o.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._kernelConnections=new Set,this._models=new Map,this._runningChanged=new s.Signal(this),this._connectionFailure=new s.Signal(this),this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:KernelManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._models.clear(),this._kernelConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}connectTo(e){var t;const{id:n}=e.model;let i=null===(t=e.handleComms)||void 0===t||t;if(void 0===e.handleComms)for(const e of this._kernelConnections)if(e.id===n&&e.handleComms){i=!1;break}const s=new l.KernelConnection({handleComms:i,...e,serverSettings:this.serverSettings});return this._onStarted(s),this._models.has(n)||this.refreshRunning().catch((()=>{})),s}running(){return this._models.values()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e={},t={}){const n=await(0,a.startNew)(e,this.serverSettings);return this.connectTo({...t,model:n})}async shutdown(e){await(0,a.shutdownKernel)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map((e=>(0,a.shutdownKernel)(e,this.serverSettings)))),await this.refreshRunning()}async findById(e){return this._models.has(e)||await this.refreshRunning(),this._models.get(e)}async requestRunning(){var e,t;let n;try{n=await(0,a.listRunning)(this.serverSettings)}catch(n){throw(n instanceof r.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}this.isDisposed||this._models.size===n.length&&n.every((e=>{const t=this._models.get(e.id);return!!t&&t.connections===e.connections&&t.execution_state===e.execution_state&&t.last_activity===e.last_activity&&t.name===e.name&&t.reason===e.reason&&t.traceback===e.traceback}))||(this._models=new Map(n.map((e=>[e.id,e]))),this._kernelConnections.forEach((e=>{this._models.has(e.id)||e.handleShutdown()})),this._runningChanged.emit(n))}_onStarted(e){this._kernelConnections.add(e),e.statusChanged.connect(this._onStatusChanged,this),e.disposed.connect(this._onDisposed,this)}_onDisposed(e){this._kernelConnections.delete(e),this.refreshRunning().catch((()=>{}))}_onStatusChanged(e,t){"dead"===t&&this.refreshRunning().catch((()=>{}))}}t.KernelManager=c,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}async startNew(e={},t={}){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}connectTo(e){throw new Error("Not implemented in no-op Kernel Manager")}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Kernel Manager"))}get ready(){return this.parentReady.then((()=>this._readyPromise))}async requestRunning(){return Promise.resolve()}}}(c=t.KernelManager||(t.KernelManager={}))},1632:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.supportedKernelWebSocketProtocols=t.isInputReplyMsg=t.isInputRequestMsg=t.isDebugReplyMsg=t.isDebugRequestMsg=t.isExecuteReplyMsg=t.isInfoRequestMsg=t.isCommMsgMsg=t.isCommCloseMsg=t.isCommOpenMsg=t.isDebugEventMsg=t.isClearOutputMsg=t.isStatusMsg=t.isErrorMsg=t.isExecuteResultMsg=t.isExecuteInputMsg=t.isUpdateDisplayDataMsg=t.isDisplayDataMsg=t.isStreamMsg=t.createMessage=void 0;const i=n(5168);t.createMessage=function(e){var t,n,s,r,o;return{buffers:null!==(t=e.buffers)&&void 0!==t?t:[],channel:e.channel,content:e.content,header:{date:(new Date).toISOString(),msg_id:null!==(n=e.msgId)&&void 0!==n?n:i.UUID.uuid4(),msg_type:e.msgType,session:e.session,username:null!==(s=e.username)&&void 0!==s?s:"",version:"5.2"},metadata:null!==(r=e.metadata)&&void 0!==r?r:{},parent_header:null!==(o=e.parentHeader)&&void 0!==o?o:{}}},t.isStreamMsg=function(e){return"stream"===e.header.msg_type},t.isDisplayDataMsg=function(e){return"display_data"===e.header.msg_type},t.isUpdateDisplayDataMsg=function(e){return"update_display_data"===e.header.msg_type},t.isExecuteInputMsg=function(e){return"execute_input"===e.header.msg_type},t.isExecuteResultMsg=function(e){return"execute_result"===e.header.msg_type},t.isErrorMsg=function(e){return"error"===e.header.msg_type},t.isStatusMsg=function(e){return"status"===e.header.msg_type},t.isClearOutputMsg=function(e){return"clear_output"===e.header.msg_type},t.isDebugEventMsg=function(e){return"debug_event"===e.header.msg_type},t.isCommOpenMsg=function(e){return"comm_open"===e.header.msg_type},t.isCommCloseMsg=function(e){return"comm_close"===e.header.msg_type},t.isCommMsgMsg=function(e){return"comm_msg"===e.header.msg_type},t.isInfoRequestMsg=function(e){return"kernel_info_request"===e.header.msg_type},t.isExecuteReplyMsg=function(e){return"execute_reply"===e.header.msg_type},t.isDebugRequestMsg=function(e){return"debug_request"===e.header.msg_type},t.isDebugReplyMsg=function(e){return"debug_reply"===e.header.msg_type},t.isInputRequestMsg=function(e){return"input_request"===e.header.msg_type},t.isInputReplyMsg=function(e){return"input_reply"===e.header.msg_type},(t.supportedKernelWebSocketProtocols||(t.supportedKernelWebSocketProtocols={})).v1KernelWebsocketJupyterOrg="v1.kernel.websocket.jupyter.org"},925:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getKernelModel=t.shutdownKernel=t.interruptKernel=t.restartKernel=t.startNew=t.listRunning=t.KERNEL_SERVICE_URL=void 0;const i=n(2700),s=n(8920),r=n(5537);t.KERNEL_SERVICE_URL="api/kernels",t.listRunning=async function(e=i.ServerConnection.makeSettings()){const n=s.URLExt.join(e.baseUrl,t.KERNEL_SERVICE_URL),o=await i.ServerConnection.makeRequest(n,{},e);if(200!==o.status)throw await i.ServerConnection.ResponseError.create(o);const a=await o.json();return(0,r.validateModels)(a),a},t.startNew=async function(e={},n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL),a={method:"POST",body:JSON.stringify(e)},l=await i.ServerConnection.makeRequest(o,a,n);if(201!==l.status)throw await i.ServerConnection.ResponseError.create(l);const c=await l.json();return(0,r.validateModel)(c),c},t.restartKernel=async function(e,n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e),"restart"),a=await i.ServerConnection.makeRequest(o,{method:"POST"},n);if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();(0,r.validateModel)(l)},t.interruptKernel=async function(e,n=i.ServerConnection.makeSettings()){const r=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e),"interrupt"),o=await i.ServerConnection.makeRequest(r,{method:"POST"},n);if(204!==o.status)throw await i.ServerConnection.ResponseError.create(o)},t.shutdownKernel=async function(e,n=i.ServerConnection.makeSettings()){const r=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e)),o=await i.ServerConnection.makeRequest(r,{method:"DELETE"},n);if(404===o.status){const t=`The kernel "${e}" does not exist on the server`;console.warn(t)}else if(204!==o.status)throw await i.ServerConnection.ResponseError.create(o)},t.getKernelModel=async function(e,n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.KERNEL_SERVICE_URL,encodeURIComponent(e)),a=await i.ServerConnection.makeRequest(o,{},n);if(404===a.status)return;if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();return(0,r.validateModel)(l),l}},7411:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.deserialize=t.serialize=void 0;const o=r(n(1632));var a;t.serialize=function(e,t=""){return t===o.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?a.serializeV1KernelWebsocketJupyterOrg(e):a.serializeDefault(e)},t.deserialize=function(e,t=""){return t===o.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg?a.deserializeV1KernelWebsocketJupyterOrg(e):a.deserializeDefault(e)},function(e){e.deserializeV1KernelWebsocketJupyterOrg=function(e){let t;const n=new DataView(e),i=Number(n.getBigUint64(0,!0));let s=[];for(let e=0;e{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateModels=t.validateModel=t.validateMessage=void 0;const i=n(8193),s=["username","version","session","msg_id","msg_type"],r={stream:{name:"string",text:"string"},display_data:{data:"object",metadata:"object"},execute_input:{code:"string",execution_count:"number"},execute_result:{execution_count:"number",data:"object",metadata:"object"},error:{ename:"string",evalue:"string",traceback:"object"},status:{execution_state:["string",["starting","idle","busy","restarting","dead"]]},clear_output:{wait:"boolean"},comm_open:{comm_id:"string",target_name:"string",data:"object"},comm_msg:{comm_id:"string",data:"object"},comm_close:{comm_id:"string"},shutdown_reply:{restart:"boolean"}};function o(e){(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"id","string")}t.validateMessage=function(e){(0,i.validateProperty)(e,"metadata","object"),(0,i.validateProperty)(e,"content","object"),(0,i.validateProperty)(e,"channel","string"),function(e){for(let t=0;to(e)))}},5312:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t},o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSpecAPI=t.KernelSpec=void 0;const a=r(n(523));t.KernelSpec=a;const l=r(n(7352));t.KernelSpecAPI=l,o(n(3973),t)},523:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},3973:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.KernelSpecManager=void 0;const o=n(5168),a=n(9033),l=n(544),c=r(n(7352)),u=n(2918);class d extends u.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._connectionFailure=new l.Signal(this),this._specs=null,this._specsChanged=new l.Signal(this),this._ready=Promise.all([this.requestSpecs()]).then((e=>{})).catch((e=>{})).then((()=>{this.isDisposed||(this._isReady=!0)})),this._pollSpecs=new a.Poll({auto:!1,factory:()=>this.requestSpecs(),frequency:{interval:61e3,backoff:!0,max:3e5},name:"@jupyterlab/services:KernelSpecManager#specs",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this.ready.then((()=>{this._pollSpecs.start()}))}get isReady(){return this._isReady}get ready(){return this._ready}get specs(){return this._specs}get specsChanged(){return this._specsChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshSpecs(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestSpecs(){const e=await c.getSpecs(this.serverSettings);this.isDisposed||o.JSONExt.deepEqual(e,this._specs)||(this._specs=e,this._specsChanged.emit(e))}}t.KernelSpecManager=d},7352:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getSpecs=void 0;const i=n(2700),s=n(7),r=n(8920);t.getSpecs=async function(e=i.ServerConnection.makeSettings()){const t=r.URLExt.join(e.baseUrl,"api/kernelspecs"),n=await i.ServerConnection.makeRequest(t,{},e);if(200!==n.status)throw await i.ServerConnection.ResponseError.create(n);const o=await n.json();return(0,s.validateSpecModels)(o)}},7:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateSpecModels=t.validateSpecModel=void 0;const i=n(8193);function s(e){const t=e.spec;if(!t)throw new Error("Invalid kernel spec");(0,i.validateProperty)(e,"name","string"),(0,i.validateProperty)(e,"resources","object"),(0,i.validateProperty)(t,"language","string"),(0,i.validateProperty)(t,"display_name","string"),(0,i.validateProperty)(t,"argv","array");let n=null;t.hasOwnProperty("metadata")&&((0,i.validateProperty)(t,"metadata","object"),n=t.metadata);let s=null;return t.hasOwnProperty("env")&&((0,i.validateProperty)(t,"env","object"),s=t.env),{name:e.name,resources:e.resources,language:t.language,display_name:t.display_name,argv:t.argv,metadata:n,env:s}}t.validateSpecModel=s,t.validateSpecModels=function(e){if(!e.hasOwnProperty("kernelspecs"))throw new Error("No kernelspecs found");let t=Object.keys(e.kernelspecs);const n=Object.create(null);let i=e.default;for(let i=0;i{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceManager=void 0;const i=n(544),s=n(1611),r=n(7593),o=n(3354),a=n(582),l=n(5312),c=n(4933),u=n(2700),d=n(7054),h=n(6052),p=n(8235),f=n(7523),m=n(87);t.ServiceManager=class{constructor(e={}){var t,n;this._isDisposed=!1,this._connectionFailure=new i.Signal(this),this._isReady=!1;const g=e.defaultDrive,v=null!==(t=e.serverSettings)&&void 0!==t?t:u.ServerConnection.makeSettings(),_={defaultDrive:g,serverSettings:v,standby:null!==(n=e.standby)&&void 0!==n?n:"when-hidden"};this.serverSettings=v,this.contents=e.contents||new r.ContentsManager(_),this.events=e.events||new o.EventManager(_),this.kernels=e.kernels||new a.KernelManager(_),this.sessions=e.sessions||new d.SessionManager({..._,kernelManager:this.kernels}),this.settings=e.settings||new h.SettingManager(_),this.terminals=e.terminals||new p.TerminalManager(_),this.builder=e.builder||new s.BuildManager(_),this.workspaces=e.workspaces||new m.WorkspaceManager(_),this.nbconvert=e.nbconvert||new c.NbConvertManager(_),this.kernelspecs=e.kernelspecs||new l.KernelSpecManager(_),this.user=e.user||new f.UserManager(_),this.kernelspecs.connectionFailure.connect(this._onConnectionFailure,this),this.sessions.connectionFailure.connect(this._onConnectionFailure,this),this.terminals.connectionFailure.connect(this._onConnectionFailure,this);const y=[this.sessions.ready,this.kernelspecs.ready];this.terminals.isAvailable()&&y.push(this.terminals.ready),this._readyPromise=Promise.all(y).then((()=>{this._isReady=!0}))}get connectionFailure(){return this._connectionFailure}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,i.Signal.clearData(this),this.contents.dispose(),this.events.dispose(),this.sessions.dispose(),this.terminals.dispose())}get isReady(){return this._isReady}get ready(){return this._readyPromise}_onConnectionFailure(e,t){this._connectionFailure.emit(t)}}},4933:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NbConvertManager=void 0;const i=n(8920),s=n(2700),r=n(5168);t.NbConvertManager=class{constructor(e={}){var t;this._exportFormats=null,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:s.ServerConnection.makeSettings()}async fetchExportFormats(){this._requestingFormats=new r.PromiseDelegate,this._exportFormats=null;const e=this.serverSettings.baseUrl,t=i.URLExt.join(e,"api/nbconvert"),{serverSettings:n}=this,o=await s.ServerConnection.makeRequest(t,{},n);if(200!==o.status)throw await s.ServerConnection.ResponseError.create(o);const a=await o.json(),l={};return Object.keys(a).forEach((function(e){const t=a[e].output_mimetype;l[e]={output_mimetype:t}})),this._exportFormats=l,this._requestingFormats.resolve(l),l}async getExportFormats(e=!0){return this._requestingFormats?this._requestingFormats.promise:e||!this._exportFormats?await this.fetchExportFormats():this._exportFormats}}},2700:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ServerConnection=void 0;const i=n(8920);let s;var r,o;s="undefined"==typeof window?n(2195):WebSocket,function(e){e.makeSettings=function(e){return o.makeSettings(e)},e.makeRequest=function(e,t,n){return o.handleRequest(e,t,n)};class t extends Error{static async create(e){try{const n=await e.json(),{message:i,traceback:s}=n;return s&&console.error(s),new t(e,null!=i?i:t._defaultMessage(e),null!=s?s:"")}catch(n){return console.debug(n),new t(e)}}constructor(e,n=t._defaultMessage(e),i=""){super(n),this.response=e,this.traceback=i}static _defaultMessage(e){return`Invalid response: ${e.status} ${e.statusText}`}}e.ResponseError=t;class n extends TypeError{constructor(e){super(e.message),this.stack=e.stack}}e.NetworkError=n}(r=t.ServerConnection||(t.ServerConnection={})),function(e){e.makeSettings=function(e={}){var t;const n=i.PageConfig.getBaseUrl(),r=i.PageConfig.getWsUrl(),o=i.URLExt.normalize(e.baseUrl)||n;let a=e.wsUrl;return a||o!==n||(a=r),a||0!==o.indexOf("http")||(a="ws"+o.slice(4)),a=null!=a?a:r,{init:{cache:"no-store",credentials:"same-origin"},fetch,Headers,Request,WebSocket:s,token:i.PageConfig.getToken(),appUrl:i.PageConfig.getOption("appUrl"),appendToken:"undefined"==typeof window||"undefined"!=typeof process&&void 0!==(null===(t=null===process||void 0===process?void 0:{})||void 0===t?void 0:t.JEST_WORKER_ID)||i.URLExt.getHostName(n)!==i.URLExt.getHostName(a),...e,baseUrl:o,wsUrl:a}},e.handleRequest=function(e,t,n){var i;if(0!==e.indexOf(n.baseUrl))throw new Error("Can only be used for notebook server requests");"no-store"===(null!==(i=t.cache)&&void 0!==i?i:n.init.cache)&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());const s=new n.Request(e,{...n.init,...t});let o=!1;if(n.token&&(o=!0,s.headers.append("Authorization",`token ${n.token}`)),"undefined"!=typeof document&&(null===document||void 0===document?void 0:document.cookie)){const e=function(e){const t=document.cookie.match("\\b_xsrf=([^;]*)\\b");return null==t?void 0:t[1]}();void 0!==e&&(o=!0,s.headers.append("X-XSRFToken",e))}return!s.headers.has("Content-Type")&&o&&s.headers.set("Content-Type","application/json"),n.fetch.call(null,s).catch((e=>{throw new r.NetworkError(e)}))}}(o||(o={}))},5575:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionConnection=void 0;const i=n(544),s=n(6914),r=n(8351),o=n(5168);t.SessionConnection=class{constructor(e){var t,n,r,a;this._id="",this._path="",this._name="",this._type="",this._kernel=null,this._isDisposed=!1,this._disposed=new i.Signal(this),this._kernelChanged=new i.Signal(this),this._statusChanged=new i.Signal(this),this._connectionStatusChanged=new i.Signal(this),this._pendingInput=new i.Signal(this),this._iopubMessage=new i.Signal(this),this._unhandledMessage=new i.Signal(this),this._anyMessage=new i.Signal(this),this._propertyChanged=new i.Signal(this),this._id=e.model.id,this._name=e.model.name,this._path=e.model.path,this._type=e.model.type,this._username=null!==(t=e.username)&&void 0!==t?t:"",this._clientId=null!==(n=e.clientId)&&void 0!==n?n:o.UUID.uuid4(),this._connectToKernel=e.connectToKernel,this._kernelConnectionOptions=null!==(r=e.kernelConnectionOptions)&&void 0!==r?r:{},this.serverSettings=null!==(a=e.serverSettings)&&void 0!==a?a:s.ServerConnection.makeSettings(),this.setupKernel(e.model.kernel)}get disposed(){return this._disposed}get kernelChanged(){return this._kernelChanged}get statusChanged(){return this._statusChanged}get connectionStatusChanged(){return this._connectionStatusChanged}get pendingInput(){return this._pendingInput}get iopubMessage(){return this._iopubMessage}get unhandledMessage(){return this._unhandledMessage}get anyMessage(){return this._anyMessage}get propertyChanged(){return this._propertyChanged}get id(){return this._id}get kernel(){return this._kernel}get path(){return this._path}get type(){return this._type}get name(){return this._name}get model(){return{id:this.id,kernel:this.kernel&&{id:this.kernel.id,name:this.kernel.name},path:this._path,type:this._type,name:this._name}}get isDisposed(){return this._isDisposed}update(e){const t=this.model;if(this._path=e.path,this._name=e.name,this._type=e.type,null===this._kernel&&null!==e.kernel||null!==this._kernel&&null===e.kernel||null!==this._kernel&&null!==e.kernel&&this._kernel.id!==e.kernel.id){null!==this._kernel&&this._kernel.dispose();const t=this._kernel||null;this.setupKernel(e.kernel);const n=this._kernel||null;this._kernelChanged.emit({name:"kernel",oldValue:t,newValue:n})}this._handleModelChange(t)}dispose(){if(!this.isDisposed){if(this._isDisposed=!0,this._disposed.emit(),this._kernel){this._kernel.dispose();const e=this._kernel;this._kernel=null;const t=this._kernel;this._kernelChanged.emit({name:"kernel",oldValue:e,newValue:t})}i.Signal.clearData(this)}}async setPath(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({path:e})}async setName(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({name:e})}async setType(e){if(this.isDisposed)throw new Error("Session is disposed");await this._patch({type:e})}async changeKernel(e){if(this.isDisposed)throw new Error("Session is disposed");return await this._patch({kernel:e}),this.kernel}async shutdown(){if(this.isDisposed)throw new Error("Session is disposed");await(0,r.shutdownSession)(this.id,this.serverSettings),this.dispose()}setupKernel(e){if(null===e)return void(this._kernel=null);const t=this._connectToKernel({...this._kernelConnectionOptions,model:e,username:this._username,clientId:this._clientId,serverSettings:this.serverSettings});this._kernel=t,t.statusChanged.connect(this.onKernelStatus,this),t.connectionStatusChanged.connect(this.onKernelConnectionStatus,this),t.pendingInput.connect(this.onPendingInput,this),t.unhandledMessage.connect(this.onUnhandledMessage,this),t.iopubMessage.connect(this.onIOPubMessage,this),t.anyMessage.connect(this.onAnyMessage,this)}onKernelStatus(e,t){this._statusChanged.emit(t)}onKernelConnectionStatus(e,t){this._connectionStatusChanged.emit(t)}onPendingInput(e,t){this._pendingInput.emit(t)}onIOPubMessage(e,t){this._iopubMessage.emit(t)}onUnhandledMessage(e,t){this._unhandledMessage.emit(t)}onAnyMessage(e,t){this._anyMessage.emit(t)}async _patch(e){const t=await(0,r.updateSession)({...e,id:this._id},this.serverSettings);return this.update(t),t}_handleModelChange(e){e.name!==this._name&&this._propertyChanged.emit("name"),e.type!==this._type&&this._propertyChanged.emit("type"),e.path!==this._path&&this._propertyChanged.emit("path")}}},7054:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),r=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return s(t,e),t},o=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SessionAPI=t.Session=void 0;const a=r(n(658));t.Session=a;const l=r(n(8351));t.SessionAPI=l,o(n(6699),t)},6699:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SessionManager=void 0;const i=n(9033),s=n(544),r=n(2700),o=n(2918),a=n(5575),l=n(8351);class c extends o.BaseManager{constructor(e){var t;super(e),this._isReady=!1,this._sessionConnections=new Set,this._models=new Map,this._runningChanged=new s.Signal(this),this._connectionFailure=new s.Signal(this),this._connectToKernel=e=>this._kernelManager.connectTo(e),this._kernelManager=e.kernelManager,this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:SessionManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._kernelManager.isActive&&await this._kernelManager.ready,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._models.clear(),this._sessionConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}connectTo(e){const t=new a.SessionConnection({...e,connectToKernel:this._connectToKernel,serverSettings:this.serverSettings});return this._onStarted(t),this._models.has(e.model.id)||this.refreshRunning().catch((()=>{})),t}running(){return this._models.values()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e,t={}){const n=await(0,l.startSession)(e,this.serverSettings);return await this.refreshRunning(),this.connectTo({...t,model:n})}async shutdown(e){await(0,l.shutdownSession)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all([...this._models.keys()].map((e=>(0,l.shutdownSession)(e,this.serverSettings)))),await this.refreshRunning()}async stopIfNeeded(e){try{const t=(await(0,l.listRunning)(this.serverSettings)).filter((t=>t.path===e));if(1===t.length){const e=t[0].id;await this.shutdown(e)}}catch(e){}}async findById(e){return this._models.has(e)||await this.refreshRunning(),this._models.get(e)}async findByPath(e){for(const t of this._models.values())if(t.path===e)return t;await this.refreshRunning();for(const t of this._models.values())if(t.path===e)return t}async requestRunning(){var e,t;let n;try{n=await(0,l.listRunning)(this.serverSettings)}catch(n){throw(n instanceof r.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}this.isDisposed||this._models.size===n.length&&n.every((e=>{var t,n,i,s;const r=this._models.get(e.id);return!!r&&(null===(t=r.kernel)||void 0===t?void 0:t.id)===(null===(n=e.kernel)||void 0===n?void 0:n.id)&&(null===(i=r.kernel)||void 0===i?void 0:i.name)===(null===(s=e.kernel)||void 0===s?void 0:s.name)&&r.name===e.name&&r.path===e.path&&r.type===e.type}))||(this._models=new Map(n.map((e=>[e.id,e]))),this._sessionConnections.forEach((e=>{this._models.has(e.id)?e.update(this._models.get(e.id)):e.dispose()})),this._runningChanged.emit(n))}_onStarted(e){this._sessionConnections.add(e),e.disposed.connect(this._onDisposed,this),e.propertyChanged.connect(this._onChanged,this),e.kernelChanged.connect(this._onChanged,this)}_onDisposed(e){this._sessionConnections.delete(e),this.refreshRunning().catch((()=>{}))}_onChanged(){this.refreshRunning().catch((()=>{}))}}t.SessionManager=c,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}async startNew(e,t={}){return Promise.reject(new Error("Not implemented in no-op Session Manager"))}connectTo(e){throw Error("Not implemented in no-op Session Manager")}get ready(){return this.parentReady.then((()=>this._readyPromise))}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Session Manager"))}async requestRunning(){return Promise.resolve()}}}(c=t.SessionManager||(t.SessionManager={}))},8351:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.updateSession=t.startSession=t.getSessionModel=t.shutdownSession=t.getSessionUrl=t.listRunning=t.SESSION_SERVICE_URL=void 0;const i=n(2700),s=n(8920),r=n(8775);function o(e,n){return s.URLExt.join(e,t.SESSION_SERVICE_URL,n)}t.SESSION_SERVICE_URL="api/sessions",t.listRunning=async function(e=i.ServerConnection.makeSettings()){const n=s.URLExt.join(e.baseUrl,t.SESSION_SERVICE_URL),o=await i.ServerConnection.makeRequest(n,{},e);if(200!==o.status)throw await i.ServerConnection.ResponseError.create(o);const a=await o.json();if(!Array.isArray(a))throw new Error("Invalid Session list");return a.forEach((e=>{(0,r.updateLegacySessionModel)(e),(0,r.validateModel)(e)})),a},t.getSessionUrl=o,t.shutdownSession=async function(e,t=i.ServerConnection.makeSettings()){var n;const s=o(t.baseUrl,e),r=await i.ServerConnection.makeRequest(s,{method:"DELETE"},t);if(404===r.status){const t=null!==(n=(await r.json()).message)&&void 0!==n?n:`The session "${e}"" does not exist on the server`;console.warn(t)}else{if(410===r.status)throw new i.ServerConnection.ResponseError(r,"The kernel was deleted but the session was not");if(204!==r.status)throw await i.ServerConnection.ResponseError.create(r)}},t.getSessionModel=async function(e,t=i.ServerConnection.makeSettings()){const n=o(t.baseUrl,e),s=await i.ServerConnection.makeRequest(n,{},t);if(200!==s.status)throw await i.ServerConnection.ResponseError.create(s);const a=await s.json();return(0,r.updateLegacySessionModel)(a),(0,r.validateModel)(a),a},t.startSession=async function(e,n=i.ServerConnection.makeSettings()){const o=s.URLExt.join(n.baseUrl,t.SESSION_SERVICE_URL),a={method:"POST",body:JSON.stringify(e)},l=await i.ServerConnection.makeRequest(o,a,n);if(201!==l.status)throw await i.ServerConnection.ResponseError.create(l);const c=await l.json();return(0,r.updateLegacySessionModel)(c),(0,r.validateModel)(c),c},t.updateSession=async function(e,t=i.ServerConnection.makeSettings()){const n=o(t.baseUrl,e.id),s={method:"PATCH",body:JSON.stringify(e)},a=await i.ServerConnection.makeRequest(n,s,t);if(200!==a.status)throw await i.ServerConnection.ResponseError.create(a);const l=await a.json();return(0,r.updateLegacySessionModel)(l),(0,r.validateModel)(l),l}},658:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},8775:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateModels=t.updateLegacySessionModel=t.validateModel=void 0;const i=n(5537),s=n(8193);function r(e){(0,s.validateProperty)(e,"id","string"),(0,s.validateProperty)(e,"type","string"),(0,s.validateProperty)(e,"name","string"),(0,s.validateProperty)(e,"path","string"),(0,s.validateProperty)(e,"kernel","object"),(0,i.validateModel)(e.kernel)}t.validateModel=r,t.updateLegacySessionModel=function(e){void 0===e.path&&void 0!==e.notebook&&(e.path=e.notebook.path,e.type="notebook",e.name="")},t.validateModels=function(e){if(!Array.isArray(e))throw new Error("Invalid session list");e.forEach((e=>r(e)))}},6052:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SettingManager=void 0;const i=n(8920),s=n(4116),r=n(2700);class o extends s.DataConnector{constructor(e={}){var t;super(),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings()}async fetch(e){if(!e)throw new Error("Plugin `id` parameter is required for settings fetch.");const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:s,ResponseError:o}=r.ServerConnection,l=n+i,c=a.url(l,e),u=await s(c,{},t);if(200!==u.status)throw await o.create(u);return u.json()}async list(e){var t,n,i,s;const{serverSettings:o}=this,{baseUrl:l,appUrl:c}=o,{makeRequest:u,ResponseError:d}=r.ServerConnection,h=l+c,p=a.url(h,"","ids"===e),f=await u(p,{},o);if(200!==f.status)throw new d(f);const m=await f.json(),g=null!==(n=null===(t=null==m?void 0:m.settings)||void 0===t?void 0:t.map((e=>e.id)))&&void 0!==n?n:[];let v=[];return e||(v=null!==(s=null===(i=null==m?void 0:m.settings)||void 0===i?void 0:i.map((e=>(e.data={composite:{},user:{}},e))))&&void 0!==s?s:[]),{ids:g,values:v}}async save(e,t){const{serverSettings:n}=this,{baseUrl:i,appUrl:s}=n,{makeRequest:o,ResponseError:l}=r.ServerConnection,c=i+s,u=a.url(c,e),d={body:JSON.stringify({raw:t}),method:"PUT"},h=await o(u,d,n);if(204!==h.status)throw new l(h)}}var a;t.SettingManager=o,function(e){e.url=function(e,t,n){const s=n?i.URLExt.objectToQueryString({ids_only:!0}):"";return`${i.URLExt.join(e,"api/settings",t)}${s}`}}(a||(a={}))},2195:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=WebSocket},5478:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TerminalConnection=void 0;const i=n(8920),s=n(5168),r=n(544),o=n(6914),a=n(4020);class l{constructor(e){var t;this._createSocket=()=>{this._errorIfDisposed(),this._clearSocket(),this._updateConnectionStatus("connecting");const e=this._name,t=this.serverSettings;let n=i.URLExt.join(t.wsUrl,"terminals","websocket",encodeURIComponent(e));const s=t.token;t.appendToken&&""!==s&&(n+=`?token=${encodeURIComponent(s)}`),this._ws=new t.WebSocket(n),this._ws.onmessage=this._onWSMessage,this._ws.onclose=this._onWSClose,this._ws.onerror=this._onWSClose},this._onWSMessage=e=>{if(this._isDisposed)return;const t=JSON.parse(e.data);"disconnect"===t[0]&&this.dispose(),"connecting"!==this._connectionStatus?this._messageReceived.emit({type:t[0],content:t.slice(1)}):"setup"===t[0]&&this._updateConnectionStatus("connected")},this._onWSClose=e=>{console.warn(`Terminal websocket closed: ${e.code}`),this.isDisposed||this._reconnect()},this._connectionStatus="connecting",this._connectionStatusChanged=new r.Signal(this),this._isDisposed=!1,this._disposed=new r.Signal(this),this._messageReceived=new r.Signal(this),this._reconnectTimeout=null,this._ws=null,this._noOp=()=>{},this._reconnectLimit=7,this._reconnectAttempt=0,this._pendingMessages=[],this._name=e.model.name,this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:o.ServerConnection.makeSettings(),this._createSocket()}get disposed(){return this._disposed}get messageReceived(){return this._messageReceived}get name(){return this._name}get model(){return{name:this._name}}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._disposed.emit(),this._updateConnectionStatus("disconnected"),this._clearSocket(),r.Signal.clearData(this))}send(e){this._sendMessage(e)}_sendMessage(e,t=!0){if(!this._isDisposed&&e.content)if("connected"===this.connectionStatus&&this._ws){const t=[e.type,...e.content];this._ws.send(JSON.stringify(t))}else{if(!t)throw new Error(`Could not send message: ${JSON.stringify(e)}`);this._pendingMessages.push(e)}}_sendPending(){for(;"connected"===this.connectionStatus&&this._pendingMessages.length>0;)this._sendMessage(this._pendingMessages[0],!1),this._pendingMessages.shift()}reconnect(){this._errorIfDisposed();const e=new s.PromiseDelegate,t=(n,i)=>{"connected"===i?(e.resolve(),this.connectionStatusChanged.disconnect(t,this)):"disconnected"===i&&(e.reject(new Error("Terminal connection disconnected")),this.connectionStatusChanged.disconnect(t,this))};return this.connectionStatusChanged.connect(t,this),this._reconnectAttempt=0,this._reconnect(),e.promise}_reconnect(){if(this._errorIfDisposed(),clearTimeout(this._reconnectTimeout),this._reconnectAttempt{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TerminalManager=void 0;const i=n(9033),s=n(544),r=n(6914),o=n(2918),a=n(4020),l=n(5478);class c extends o.BaseManager{constructor(e={}){var t;if(super(e),this._isReady=!1,this._names=[],this._terminalConnections=new Set,this._runningChanged=new s.Signal(this),this._connectionFailure=new s.Signal(this),!this.isAvailable())return this._ready=Promise.reject("Terminals unavailable"),void this._ready.catch((e=>{}));this._pollModels=new i.Poll({auto:!1,factory:()=>this.requestRunning(),frequency:{interval:1e4,backoff:!0,max:3e5},name:"@jupyterlab/services:TerminalManager#models",standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this._ready=(async()=>{await this._pollModels.start(),await this._pollModels.tick,this._isReady=!0})()}get isReady(){return this._isReady}get ready(){return this._ready}get runningChanged(){return this._runningChanged}get connectionFailure(){return this._connectionFailure}dispose(){this.isDisposed||(this._names.length=0,this._terminalConnections.forEach((e=>e.dispose())),this._pollModels.dispose(),super.dispose())}isAvailable(){return(0,a.isAvailable)()}connectTo(e){const t=new l.TerminalConnection({...e,serverSettings:this.serverSettings});return this._onStarted(t),this._names.includes(e.model.name)||this.refreshRunning().catch((()=>{})),t}running(){return this._models[Symbol.iterator]()}async refreshRunning(){await this._pollModels.refresh(),await this._pollModels.tick}async startNew(e){const t=await(0,a.startNew)(this.serverSettings,null==e?void 0:e.name,null==e?void 0:e.cwd);return await this.refreshRunning(),this.connectTo({model:t})}async shutdown(e){await(0,a.shutdownTerminal)(e,this.serverSettings),await this.refreshRunning()}async shutdownAll(){await this.refreshRunning(),await Promise.all(this._names.map((e=>(0,a.shutdownTerminal)(e,this.serverSettings)))),await this.refreshRunning()}async requestRunning(){var e,t;let n;try{n=await(0,a.listRunning)(this.serverSettings)}catch(n){throw(n instanceof r.ServerConnection.NetworkError||503===(null===(e=n.response)||void 0===e?void 0:e.status)||424===(null===(t=n.response)||void 0===t?void 0:t.status))&&this._connectionFailure.emit(n),n}if(this.isDisposed)return;const i=n.map((({name:e})=>e)).sort();i!==this._names&&(this._names=i,this._terminalConnections.forEach((e=>{i.includes(e.name)||e.dispose()})),this._runningChanged.emit(this._models))}_onStarted(e){this._terminalConnections.add(e),e.disposed.connect(this._onDisposed,this)}_onDisposed(e){this._terminalConnections.delete(e),this.refreshRunning().catch((()=>{}))}get _models(){return this._names.map((e=>({name:e})))}}t.TerminalManager=c,function(e){e.NoopManager=class extends e{constructor(){super(...arguments),this._readyPromise=new Promise((()=>{}))}get isActive(){return!1}get parentReady(){return super.ready}get ready(){return this.parentReady.then((()=>this._readyPromise))}async startNew(e){return Promise.reject(new Error("Not implemented in no-op Terminal Manager"))}connectTo(e){throw Error("Not implemented in no-op Terminal Manager")}async shutdown(e){return Promise.reject(new Error("Not implemented in no-op Terminal Manager"))}async requestRunning(){return Promise.resolve()}}}(c=t.TerminalManager||(t.TerminalManager={}))},4020:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shutdownTerminal=t.listRunning=t.startNew=t.isAvailable=t.TERMINAL_SERVICE_URL=void 0;const i=n(8920),s=n(2700);function r(){return"true"===String(i.PageConfig.getOption("terminalsAvailable")).toLowerCase()}var o;t.TERMINAL_SERVICE_URL="api/terminals",t.isAvailable=r,t.startNew=async function(e=s.ServerConnection.makeSettings(),n,r){o.errorIfNotAvailable();const a=i.URLExt.join(e.baseUrl,t.TERMINAL_SERVICE_URL),l={method:"POST",body:JSON.stringify({name:n,cwd:r})},c=await s.ServerConnection.makeRequest(a,l,e);if(200!==c.status)throw await s.ServerConnection.ResponseError.create(c);return await c.json()},t.listRunning=async function(e=s.ServerConnection.makeSettings()){o.errorIfNotAvailable();const n=i.URLExt.join(e.baseUrl,t.TERMINAL_SERVICE_URL),r=await s.ServerConnection.makeRequest(n,{},e);if(200!==r.status)throw await s.ServerConnection.ResponseError.create(r);const a=await r.json();if(!Array.isArray(a))throw new Error("Invalid terminal list");return a},t.shutdownTerminal=async function(e,n=s.ServerConnection.makeSettings()){var r;o.errorIfNotAvailable();const a=i.URLExt.join(n.baseUrl,t.TERMINAL_SERVICE_URL,e),l=await s.ServerConnection.makeRequest(a,{method:"DELETE"},n);if(404===l.status){const t=null!==(r=(await l.json()).message)&&void 0!==r?r:`The terminal session "${e}"" does not exist on the server`;console.warn(t)}else if(204!==l.status)throw await s.ServerConnection.ResponseError.create(l)},function(e){e.errorIfNotAvailable=function(){if(!r())throw new Error("Terminals Unavailable")}}(o||(o={}))},4468:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isAvailable=void 0;const i=n(4020);Object.defineProperty(t,"isAvailable",{enumerable:!0,get:function(){return i.isAvailable}})},7523:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UserManager=void 0;const i=n(8920),s=n(5168),r=n(9033),o=n(544),a=n(2700),l=n(2918),c="@jupyterlab/services:UserManager#user";class u extends l.BaseManager{constructor(e={}){var t;super(e),this._isReady=!1,this._userChanged=new o.Signal(this),this._connectionFailure=new o.Signal(this),this._ready=this.requestUser().then((()=>{this.isDisposed||(this._isReady=!0)})).catch((e=>new Promise((()=>{})))),this._pollSpecs=new r.Poll({auto:!1,factory:()=>this.requestUser(),frequency:{interval:61e3,backoff:!0,max:3e5},name:c,standby:null!==(t=e.standby)&&void 0!==t?t:"when-hidden"}),this.ready.then((()=>{this._pollSpecs.start()}))}get isReady(){return this._isReady}get ready(){return this._ready}get identity(){return this._identity}get permissions(){return this._permissions}get userChanged(){return this._userChanged}get connectionFailure(){return this._connectionFailure}dispose(){this._pollSpecs.dispose(),super.dispose()}async refreshUser(){await this._pollSpecs.refresh(),await this._pollSpecs.tick}async requestUser(){if(this.isDisposed)return;const{baseUrl:e}=this.serverSettings,{makeRequest:t,ResponseError:n}=a.ServerConnection,r=i.URLExt.join(e,"api/me"),o=await t(r,{},this.serverSettings);if(200!==o.status)throw await n.create(o);const l={identity:this._identity,permissions:this._permissions},u=await o.json(),h=u.identity,{localStorage:p}=window,f=p.getItem(c);if(f&&(!h.initials||!h.color)){const e=JSON.parse(f);h.initials=h.initials||e.initials||h.name.substring(0,1),h.color=h.color||e.color||d.getRandomColor()}s.JSONExt.deepEqual(u,l)||(this._identity=h,this._permissions=u.permissions,p.setItem(c,JSON.stringify(h)),this._userChanged.emit(u))}}var d;t.UserManager=u,function(e){const t=["var(--jp-collaborator-color1)","var(--jp-collaborator-color2)","var(--jp-collaborator-color3)","var(--jp-collaborator-color4)","var(--jp-collaborator-color5)","var(--jp-collaborator-color6)","var(--jp-collaborator-color7)"];e.getRandomColor=()=>t[Math.floor(Math.random()*t.length)]}(d||(d={}))},8193:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.validateProperty=void 0,t.validateProperty=function(e,t,n,i=[]){if(!e.hasOwnProperty(t))throw Error(`Missing property '${t}'`);const s=e[t];if(void 0!==n){let e=!0;switch(n){case"array":e=Array.isArray(s);break;case"object":e=void 0!==s;break;default:e=typeof s===n}if(!e)throw new Error(`Property '${t}' is not of type '${n}'`);if(i.length>0){let e=!0;switch(n){case"string":case"number":case"boolean":e=i.includes(s);break;default:e=i.findIndex((e=>e===s))>=0}if(!e)throw new Error(`Property '${t}' is not one of the valid values ${JSON.stringify(i)}`)}}}},87:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WorkspaceManager=void 0;const i=n(8920),s=n(4116),r=n(2700);class o extends s.DataConnector{constructor(e={}){var t;super(),this.serverSettings=null!==(t=e.serverSettings)&&void 0!==t?t:r.ServerConnection.makeSettings()}async fetch(e){const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:s,ResponseError:o}=r.ServerConnection,l=n+i,c=a.url(l,e),u=await s(c,{},t);if(200!==u.status)throw await o.create(u);return u.json()}async list(){const{serverSettings:e}=this,{baseUrl:t,appUrl:n}=e,{makeRequest:i,ResponseError:s}=r.ServerConnection,o=t+n,l=a.url(o,""),c=await i(l,{},e);if(200!==c.status)throw await s.create(c);return(await c.json()).workspaces}async remove(e){const{serverSettings:t}=this,{baseUrl:n,appUrl:i}=t,{makeRequest:s,ResponseError:o}=r.ServerConnection,l=n+i,c=a.url(l,e),u=await s(c,{method:"DELETE"},t);if(204!==u.status)throw await o.create(u)}async save(e,t){const{serverSettings:n}=this,{baseUrl:i,appUrl:s}=n,{makeRequest:o,ResponseError:l}=r.ServerConnection,c=i+s,u=a.url(c,e),d={body:JSON.stringify(t),method:"PUT"},h=await o(u,d,n);if(204!==h.status)throw await l.create(h)}}var a;t.WorkspaceManager=o,function(e){e.url=function(e,t){return i.URLExt.join(e,"api/workspaces",t)}}(a||(a={}))},5619:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityMonitor=void 0;const i=n(544);t.ActivityMonitor=class{constructor(e){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new i.Signal(this),e.signal.connect(this._onSignalFired,this),this._timeout=e.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(e){this._timeout=e}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,i.Signal.clearData(this))}_onSignalFired(e,t){clearTimeout(this._timer),this._sender=e,this._args=t,this._timer=setTimeout((()=>{this._activityStopped.emit({sender:this._sender,args:this._args})}),this._timeout)}}},8920:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(5619),t),s(n(8769),t),s(n(4612),t),s(n(9230),t),s(n(7034),t),s(n(902),t),s(n(6400),t),s(n(1718),t),s(n(8305),t)},8769:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},4612:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MarkdownCodeBlocks=void 0,function(e){e.CODE_BLOCK_MARKER="```";const t=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class n{constructor(e){this.startLine=e,this.code="",this.endLine=-1}}e.MarkdownCodeBlock=n,e.isMarkdown=function(e){return t.indexOf(e)>-1},e.findMarkdownCodeBlocks=function(t){if(!t||""===t)return[];const i=t.split("\n"),s=[];let r=null;for(let t=0;te===t||i&&e===i))},e.isDisabled=function(t){const n=t.indexOf(":");let i="";return-1!==n&&(i=t.slice(0,n)),e.disabled.some((e=>e===t||i&&e===i))}}(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))},7034:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PathExt=void 0;const i=n(1023);!function(e){function t(e){return 0===e.indexOf("/")&&(e=e.slice(1)),e}e.join=function(...e){const n=i.posix.join(...e);return"."===n?"":t(n)},e.basename=function(e,t){return i.posix.basename(e,t)},e.dirname=function(e){const n=t(i.posix.dirname(e));return"."===n?"":n},e.extname=function(e){return i.posix.extname(e)},e.normalize=function(e){return""===e?"":t(i.posix.normalize(e))},e.resolve=function(...e){return t(i.posix.resolve(...e))},e.relative=function(e,n){return t(i.posix.relative(e,n))},e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e},e.removeSlash=t}(t.PathExt||(t.PathExt={}))},902:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalToPromise=void 0;const i=n(5168);t.signalToPromise=function(e,t){const n=new i.PromiseDelegate;function s(){e.disconnect(r)}function r(e,t){s(),n.resolve([e,t])}return e.connect(r),(null!=t?t:0)>0&&setTimeout((()=>{s(),n.reject(`Signal not emitted within ${t} ms.`)}),t),n.promise}},6400:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Text=void 0,function(e){const t="𝐚".length>1;e.jsIndexToCharIndex=function(e,n){if(t)return e;let i=e;for(let t=0;t+1=55296&&e<=56319){const e=n.charCodeAt(t+1);e>=56320&&e<=57343&&(i--,t++)}}return i},e.charIndexToJsIndex=function(e,n){if(t)return e;let i=e;for(let e=0;e+1=55296&&t<=56319){const t=n.charCodeAt(e+1);t>=56320&&t<=57343&&(i++,e++)}}return i},e.camelCase=function(e,t=!1){return e.replace(/^(\w)|[\s-_:]+(\w)/g,(function(e,n,i){return i?i.toUpperCase():t?n.toUpperCase():n.toLowerCase()}))},e.titleCase=function(e){return(e||"").toLowerCase().split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(" ")}}(t.Text||(t.Text={}))},1718:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Time=void 0;const n=[{name:"years",milliseconds:31536e6},{name:"months",milliseconds:2592e6},{name:"days",milliseconds:864e5},{name:"hours",milliseconds:36e5},{name:"minutes",milliseconds:6e4},{name:"seconds",milliseconds:1e3}];var i;(i=t.Time||(t.Time={})).formatHuman=function(e){const t=document.documentElement.lang||"en",i=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),s=new Date(e).getTime()-Date.now();for(let e of n){const t=Math.ceil(s/e.milliseconds);if(0!==t)return i.format(t,e.name)}return i.format(0,"seconds")},i.format=function(e){const t=document.documentElement.lang||"en";return new Intl.DateTimeFormat(t,{dateStyle:"short",timeStyle:"short"}).format(new Date(e))}},8305:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.URLExt=void 0;const s=n(1023),r=i(n(4846));!function(e){function t(e){if("undefined"!=typeof document&&document){const t=document.createElement("a");return t.href=e,t}return(0,r.default)(e)}function n(...e){let t=(0,r.default)(e[0],{});const n=""===t.protocol&&t.slashes;n&&(t=(0,r.default)(e[0],"https:"+e[0]));const i=`${n?"":t.protocol}${t.slashes?"//":""}${t.auth}${t.auth?"@":""}${t.host}`,o=s.posix.join(`${i&&"/"!==t.pathname[0]?"/":""}${t.pathname}`,...e.slice(1));return`${i}${"."===o?"":o}`}e.parse=t,e.getHostName=function(e){return(0,r.default)(e).hostname},e.normalize=function(e){return e&&t(e).toString()},e.join=n,e.encodeParts=function(e){return n(...e.split("/").map(encodeURIComponent))},e.objectToQueryString=function(e){const t=Object.keys(e).filter((e=>e.length>0));return t.length?"?"+t.map((t=>{const n=encodeURIComponent(String(e[t]));return t+(n?"="+n:"")})).join("&"):""},e.queryStringToObject=function(e){return e.replace(/^\?/,"").split("&").reduce(((e,t)=>{const[n,i]=t.split("=");return n.length>0&&(e[n]=decodeURIComponent(i||"")),e}),{})},e.isLocal=function(e){const{protocol:n}=t(e);return(!n||0!==e.toLowerCase().indexOf(n))&&0!==e.indexOf("/")}}(t.URLExt||(t.URLExt={}))},2845:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnector=void 0,t.DataConnector=class{async list(e){throw new Error("DataConnector#list method has not been implemented.")}async remove(e){throw new Error("DataConnector#remove method has not been implemented.")}async save(e,t){throw new Error("DataConnector#save method has not been implemented.")}}},4116:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(2845),t),s(n(3288),t),s(n(4803),t),s(n(6165),t),s(n(9329),t)},3288:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},4803:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RestorablePool=void 0;const i=n(5168),s=n(2571),r=n(544);var o;t.RestorablePool=class{constructor(e){this._added=new r.Signal(this),this._current=null,this._currentChanged=new r.Signal(this),this._hasRestored=!1,this._isDisposed=!1,this._objects=new Set,this._restore=null,this._restored=new i.PromiseDelegate,this._updated=new r.Signal(this),this.namespace=e.namespace}get added(){return this._added}get current(){return this._current}set current(e){this._current!==e&&null!==e&&this._objects.has(e)&&(this._current=e,this._currentChanged.emit(this._current))}get currentChanged(){return this._currentChanged}get isDisposed(){return this._isDisposed}get restored(){return this._restored.promise}get size(){return this._objects.size}get updated(){return this._updated}async add(e){var t,n;if(e.isDisposed){const t="A disposed object cannot be added.";throw console.warn(t,e),new Error(t)}if(this._objects.has(e)){const t="This object already exists in the pool.";throw console.warn(t,e),new Error(t)}if(this._objects.add(e),e.disposed.connect(this._onInstanceDisposed,this),!o.injectedProperty.get(e)){if(this._restore){const{connector:i}=this._restore,s=this._restore.name(e);if(s){const r=`${this.namespace}:${s}`,a=null===(n=(t=this._restore).args)||void 0===n?void 0:n.call(t,e);o.nameProperty.set(e,r),await i.save(r,{data:a})}}this._added.emit(e)}}dispose(){this.isDisposed||(this._current=null,this._isDisposed=!0,this._objects.clear(),r.Signal.clearData(this))}find(e){const t=this._objects.values();for(const n of t)if(e(n))return n}forEach(e){this._objects.forEach(e)}filter(e){const t=[];return this.forEach((n=>{e(n)&&t.push(n)})),t}inject(e){return o.injectedProperty.set(e,!0),this.add(e)}has(e){return this._objects.has(e)}async restore(e){if(this._hasRestored)throw new Error("This pool has already been restored.");this._hasRestored=!0;const{command:t,connector:n,registry:i,when:s}=e,r=this.namespace,o=s?[n.list(r)].concat(s):[n.list(r)];this._restore=e;const[a]=await Promise.all(o),l=await Promise.all(a.ids.map((async(e,s)=>{const r=a.values[s],o=r&&r.data;return void 0===o?n.remove(e):i.execute(t,o).catch((()=>n.remove(e)))})));return this._restored.resolve(),l}async save(e){var t,n;const i=o.injectedProperty.get(e);if(!this._restore||!this.has(e)||i)return;const{connector:s}=this._restore,r=this._restore.name(e),a=o.nameProperty.get(e),l=r?`${this.namespace}:${r}`:"";if(a&&a!==l&&await s.remove(a),o.nameProperty.set(e,l),l){const i=null===(n=(t=this._restore).args)||void 0===n?void 0:n.call(t,e);await s.save(l,{data:i})}a!==l&&this._updated.emit(e)}_onInstanceDisposed(e){if(this._objects.delete(e),e===this._current&&(this._current=null,this._currentChanged.emit(this._current)),o.injectedProperty.get(e))return;if(!this._restore)return;const{connector:t}=this._restore,n=o.nameProperty.get(e);n&&t.remove(n)}},function(e){e.injectedProperty=new s.AttachedProperty({name:"injected",create:()=>!1}),e.nameProperty=new s.AttachedProperty({name:"name",create:()=>""})}(o||(o={}))},6165:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.StateDB=void 0;const i=n(544);class s{constructor(e={}){this._changed=new i.Signal(this);const{connector:t,transform:n}=e;this._connector=t||new s.Connector,this._ready=n?n.then((e=>{const{contents:t,type:n}=e;switch(n){case"cancel":default:return;case"clear":return this._clear();case"merge":return this._merge(t||{});case"overwrite":return this._overwrite(t||{})}})):Promise.resolve(void 0)}get changed(){return this._changed}async clear(){await this._ready,await this._clear()}async fetch(e){return await this._ready,this._fetch(e)}async list(e){return await this._ready,this._list(e)}async remove(e){await this._ready,await this._remove(e),this._changed.emit({id:e,type:"remove"})}async save(e,t){await this._ready,await this._save(e,t),this._changed.emit({id:e,type:"save"})}async toJSON(){await this._ready;const{ids:e,values:t}=await this._list();return t.reduce(((t,n,i)=>(t[e[i]]=n,t)),{})}async _clear(){await Promise.all((await this._list()).ids.map((e=>this._remove(e))))}async _fetch(e){const t=await this._connector.fetch(e);if(t)return JSON.parse(t).v}async _list(e=""){const{ids:t,values:n}=await this._connector.list(e);return{ids:t,values:n.map((e=>JSON.parse(e).v))}}async _merge(e){await Promise.all(Object.keys(e).map((t=>e[t]&&this._save(t,e[t]))))}async _overwrite(e){await this._clear(),await this._merge(e)}async _remove(e){return this._connector.remove(e)}async _save(e,t){return this._connector.save(e,JSON.stringify({v:t}))}}t.StateDB=s,function(e){e.Connector=class{constructor(){this._storage={}}async fetch(e){return this._storage[e]}async list(e=""){return Object.keys(this._storage).reduce(((t,n)=>(""!==e&&e!==n.split(":")[0]||(t.ids.push(n),t.values.push(this._storage[n])),t)),{ids:[],values:[]})}async remove(e){delete this._storage[e]}async save(e,t){this._storage[e]=t}}}(s=t.StateDB||(t.StateDB={}))},9329:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IStateDB=void 0;const i=n(5168);t.IStateDB=new i.Token("@jupyterlab/coreutils:IStateDB",'A service for the JupyterLab state database.\n Use this if you want to store data that will persist across page loads.\n See "state database" for more information.')},5168:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},4643:(e,t,n)=>{"use strict";n.r(t),n.d(t,{DisposableDelegate:()=>s,DisposableSet:()=>o,ObservableDisposableDelegate:()=>r,ObservableDisposableSet:()=>a});var i=n(544);class s{constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class r extends s{constructor(){super(...arguments),this._disposed=new i.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),i.Signal.clearData(this))}}class o{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(o||(o={}));class a extends o{constructor(){super(...arguments),this._disposed=new i.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),i.Signal.clearData(this))}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(a||(a={}))},9033:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Debouncer:()=>l,Poll:()=>o,RateLimiter:()=>a,Throttler:()=>c});var i,s=n(5168),r=n(544);class o{constructor(e){var t;this._disposed=new r.Signal(this),this._lingered=0,this._tick=new s.PromiseDelegate,this._ticked=new r.Signal(this),this._factory=e.factory,this._linger=null!==(t=e.linger)&&void 0!==t?t:i.DEFAULT_LINGER,this._standby=e.standby||i.DEFAULT_STANDBY,this._state={...i.DEFAULT_STATE,timestamp:(new Date).getTime()};const n=e.frequency||{},o=Math.max(n.interval||0,n.max||0,i.DEFAULT_FREQUENCY.max);this.frequency={...i.DEFAULT_FREQUENCY,...n,max:o},this.name=e.name||i.DEFAULT_NAME,"auto"in e&&!e.auto||setTimeout((()=>this.start()))}get disposed(){return this._disposed}get frequency(){return this._frequency}set frequency(e){if(this.isDisposed||s.JSONExt.deepEqual(e,this.frequency||{}))return;let{backoff:t,interval:n,max:i}=e;if(n=Math.round(n),i=Math.round(i),"number"==typeof t&&t<1)throw new Error("Poll backoff growth factor must be at least 1");if((n<0||n>i)&&n!==o.NEVER)throw new Error("Poll interval must be between 0 and max");if(i>o.MAX_INTERVAL&&i!==o.NEVER)throw new Error(`Max interval must be less than ${o.MAX_INTERVAL}`);this._frequency={backoff:t,interval:n,max:i}}get isDisposed(){return"disposed"===this.state.phase}get standby(){return this._standby}set standby(e){this.isDisposed||this.standby===e||(this._standby=e)}get state(){return this._state}get tick(){return this._tick.promise}get ticked(){return this._ticked}async*[Symbol.asyncIterator](){for(;!this.isDisposed;)yield this.state,await this.tick.catch((()=>{}))}dispose(){this.isDisposed||(this._state={...i.DISPOSED_STATE,timestamp:(new Date).getTime()},this._tick.promise.catch((e=>{})),this._tick.reject(new Error(`Poll (${this.name}) is disposed.`)),this._disposed.emit(void 0),r.Signal.clearData(this))}refresh(){return this.schedule({cancel:({phase:e})=>"refreshed"===e,interval:o.IMMEDIATE,phase:"refreshed"})}async schedule(e={}){if(this.isDisposed)return;if(e.cancel&&e.cancel(this.state))return;const t=this._tick,n=new s.PromiseDelegate,i={interval:this.frequency.interval,payload:null,phase:"standby",timestamp:(new Date).getTime(),...e};this._state=i,this._tick=n,clearTimeout(this._timeout),this._ticked.emit(this.state),t.resolve(this),await t.promise,i.interval!==o.NEVER?this._timeout=setTimeout((()=>{this.isDisposed||this.tick!==n.promise||this._execute()}),i.interval):this._timeout=void 0}start(){return this.schedule({cancel:({phase:e})=>"constructed"!==e&&"standby"!==e&&"stopped"!==e,interval:o.IMMEDIATE,phase:"started"})}stop(){return this.schedule({cancel:({phase:e})=>"stopped"===e,interval:o.NEVER,phase:"stopped"})}get hidden(){return i.hidden}_execute(){let e="function"==typeof this.standby?this.standby():this.standby;if("never"===e?e=!1:"when-hidden"===e&&(this.hidden?e=++this._lingered>this._linger:(this._lingered=0,e=!1)),e)return void this.schedule();const t=this.tick;this._factory(this.state).then((e=>{this.isDisposed||this.tick!==t||this.schedule({payload:e,phase:"rejected"===this.state.phase?"reconnected":"resolved"})})).catch((e=>{this.isDisposed||this.tick!==t||this.schedule({interval:i.sleep(this.frequency,this.state),payload:e,phase:"rejected"})}))}}!function(e){e.IMMEDIATE=0,e.MAX_INTERVAL=2147483647,e.NEVER=1/0}(o||(o={})),function(e){e.DEFAULT_BACKOFF=3,e.DEFAULT_FREQUENCY={backoff:!0,interval:1e3,max:3e4},e.DEFAULT_LINGER=1,e.DEFAULT_NAME="unknown",e.DEFAULT_STANDBY="when-hidden",e.DEFAULT_STATE={interval:o.NEVER,payload:null,phase:"constructed",timestamp:new Date(0).getTime()},e.DISPOSED_STATE={interval:o.NEVER,payload:null,phase:"disposed",timestamp:new Date(0).getTime()},e.sleep=function(t,n){const{backoff:i,interval:s,max:r}=t;if(s===o.NEVER)return s;const a=!0===i?e.DEFAULT_BACKOFF:!1===i?1:i,l=function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e}(s,n.interval*a);return Math.min(r,l)},e.hidden="undefined"!=typeof document&&(document.addEventListener("visibilitychange",(()=>{e.hidden="hidden"===document.visibilityState})),document.addEventListener("pagehide",(()=>{e.hidden="hidden"===document.visibilityState})),"hidden"===document.visibilityState)}(i||(i={}));class a{constructor(e,t=500){this.args=void 0,this.payload=null,this.limit=t,this.poll=new o({auto:!1,factory:async()=>{const{args:t}=this;return this.args=void 0,e(...t)},frequency:{backoff:!1,interval:o.NEVER,max:o.NEVER},standby:"never"}),this.payload=new s.PromiseDelegate,this.poll.ticked.connect(((e,t)=>{const{payload:n}=this;return"resolved"===t.phase?(this.payload=new s.PromiseDelegate,void n.resolve(t.payload)):"rejected"===t.phase||"stopped"===t.phase?(this.payload=new s.PromiseDelegate,n.promise.catch((e=>{})),void n.reject(t.payload)):void 0}),this)}get isDisposed(){return null===this.payload}dispose(){this.isDisposed||(this.args=void 0,this.payload=null,this.poll.dispose())}async stop(){return this.poll.stop()}}class l extends a{invoke(...e){return this.args=e,this.poll.schedule({interval:this.limit,phase:"invoked"}),this.payload.promise}}class c extends a{constructor(e,t){super(e,"number"==typeof t?t:t&&t.limit),this._trailing=!1,"number"!=typeof t&&t&&"trailing"===t.edge&&(this._trailing=!0),this._interval=this._trailing?this.limit:o.IMMEDIATE}invoke(...e){const t="invoked"!==this.poll.state.phase;return(t||this._trailing)&&(this.args=e),t&&this.poll.schedule({interval:this._interval,phase:"invoked"}),this.payload.promise}}},2571:(e,t,n)=>{"use strict";n.r(t),n.d(t,{AttachedProperty:()=>i});class i{constructor(e){this._pid=s.nextPID(),this.name=e.name,this._create=e.create,this._coerce=e.coerce||null,this._compare=e.compare||null,this._changed=e.changed||null}get(e){let t,n=s.ensureMap(e);return t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e),t}set(e,t){let n,i=s.ensureMap(e);n=this._pid in i?i[this._pid]:i[this._pid]=this._createValue(e);let r=this._coerceValue(e,t);this._maybeNotify(e,n,i[this._pid]=r)}coerce(e){let t,n=s.ensureMap(e);t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e);let i=this._coerceValue(e,t);this._maybeNotify(e,t,n[this._pid]=i)}_createValue(e){return(0,this._create)(e)}_coerceValue(e,t){let n=this._coerce;return n?n(e,t):t}_compareValue(e,t){let n=this._compare;return n?n(e,t):e===t}_maybeNotify(e,t,n){let i=this._changed;i&&!this._compareValue(t,n)&&i(e,t,n)}}var s;!function(e){e.clearData=function(e){s.ownerData.delete(e)}}(i||(i={})),function(e){e.ownerData=new WeakMap,e.nextPID=(()=>{let e=0;return()=>`pid-${`${Math.random()}`.slice(2)}-${e++}`})(),e.ensureMap=function(t){let n=e.ownerData.get(t);return n||(n=Object.create(null),e.ownerData.set(t,n),n)}}(s||(s={}))},544:(e,t,n)=>{"use strict";var i,s,r;n.r(t),n.d(t,{Signal:()=>l,Stream:()=>c}),function(e){function t(e,t,n=0,i=-1){let s,r=e.length;if(0===r)return-1;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(i||(i={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(r||(r={}));var o,a=n(5168);class l{constructor(e){this.sender=e}connect(e,t){return o.connect(this,e,t)}disconnect(e,t){return o.disconnect(this,e,t)}emit(e){o.emit(this,e)}}!function(e){e.disconnectBetween=function(e,t){o.disconnectBetween(e,t)},e.disconnectSender=function(e){o.disconnectSender(e)},e.disconnectReceiver=function(e){o.disconnectReceiver(e)},e.disconnectAll=function(e){o.disconnectAll(e)},e.clearData=function(e){o.disconnectAll(e)},e.getExceptionHandler=function(){return o.exceptionHandler},e.setExceptionHandler=function(e){let t=o.exceptionHandler;return o.exceptionHandler=e,t}}(l||(l={}));class c extends l{constructor(){super(...arguments),this._pending=new a.PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new a.PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new a.PromiseDelegate}}!function(e){function t(e){let t=s.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,u(r.get(t))}u(t)}}function n(e){let t=r.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,u(s.get(t))}u(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let i=s.get(e.sender);if(i||(i=[],s.set(e.sender,i)),l(i,e,t,n))return!1;let o=n||t,a=r.get(o);a||(a=[],r.set(o,a));let c={signal:e,slot:t,thisArg:n};return i.push(c),a.push(c),!0},e.disconnect=function(e,t,n){n=n||void 0;let i=s.get(e.sender);if(!i||0===i.length)return!1;let o=l(i,e,t,n);if(!o)return!1;let a=n||t,c=r.get(a);return o.signal=null,u(i),u(c),!0},e.disconnectBetween=function(e,t){let n=s.get(e);if(!n||0===n.length)return;let i=r.get(t);if(i&&0!==i.length){for(const t of i)t.signal&&t.signal.sender===e&&(t.signal=null);u(n),u(i)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=s.get(e.sender);if(n&&0!==n.length)for(let i=0,s=n.length;i>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},6111:function(e){e.exports=function(){"use strict";function e(e,t){return e(t={exports:{}},t.exports),t.exports}var t=e((function(e){var t=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=t)})),n=e((function(e){var t=e.exports={version:"2.6.5"};"number"==typeof __e&&(__e=t)})),i=(n.version,function(e){return"object"==typeof e?null!==e:"function"==typeof e}),s=function(e){if(!i(e))throw TypeError(e+" is not an object!");return e},r=function(e){try{return!!e()}catch(e){return!0}},o=!r((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})),a=t.document,l=i(a)&&i(a.createElement),c=!o&&!r((function(){return 7!=Object.defineProperty((e="div",l?a.createElement(e):{}),"a",{get:function(){return 7}}).a;var e})),u=Object.defineProperty,d={f:o?Object.defineProperty:function(e,t,n){if(s(e),t=function(e,t){if(!i(e))return e;var n,s;if(t&&"function"==typeof(n=e.toString)&&!i(s=n.call(e)))return s;if("function"==typeof(n=e.valueOf)&&!i(s=n.call(e)))return s;if(!t&&"function"==typeof(n=e.toString)&&!i(s=n.call(e)))return s;throw TypeError("Can't convert object to primitive value")}(t,!0),s(n),c)try{return u(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},h=o?function(e,t,n){return d.f(e,t,function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}(1,n))}:function(e,t,n){return e[t]=n,e},p={}.hasOwnProperty,f=function(e,t){return p.call(e,t)},m=0,g=Math.random(),v=e((function(e){var i="__core-js_shared__",s=t[i]||(t[i]={});(e.exports=function(e,t){return s[e]||(s[e]=void 0!==t?t:{})})("versions",[]).push({version:n.version,mode:"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})})),_=v("native-function-to-string",Function.toString),y=e((function(e){var i=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++m+g).toString(36))}("src"),s="toString",r=(""+_).split(s);n.inspectSource=function(e){return _.call(e)},(e.exports=function(e,n,s,o){var a="function"==typeof s;a&&(f(s,"name")||h(s,"name",n)),e[n]!==s&&(a&&(f(s,i)||h(s,i,e[n]?""+e[n]:r.join(String(n)))),e===t?e[n]=s:o?e[n]?e[n]=s:h(e,n,s):(delete e[n],h(e,n,s)))})(Function.prototype,s,(function(){return"function"==typeof this&&this[i]||_.call(this)}))})),b=function(e,t,n){if(function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!")}(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,i){return e.call(t,n,i)};case 3:return function(n,i,s){return e.call(t,n,i,s)}}return function(){return e.apply(t,arguments)}},w="prototype",D=function(e,i,s){var r,o,a,l,c=e&D.F,u=e&D.G,d=e&D.S,p=e&D.P,f=e&D.B,m=u?t:d?t[i]||(t[i]={}):(t[i]||{})[w],g=u?n:n[i]||(n[i]={}),v=g[w]||(g[w]={});for(r in u&&(s=i),s)a=((o=!c&&m&&void 0!==m[r])?m:s)[r],l=f&&o?b(a,t):p&&"function"==typeof a?b(Function.call,a):a,m&&y(m,r,a,e&D.U),g[r]!=a&&h(g,r,l),p&&v[r]!=a&&(v[r]=a)};t.core=n,D.F=1,D.G=2,D.S=4,D.P=8,D.B=16,D.W=32,D.U=64,D.R=128;var x=D,C=Math.ceil,E=Math.floor,S=function(e){return isNaN(e=+e)?0:(e>0?E:C)(e)},A=(!1,function(e,t){var n,i,s=String(function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}(e)),r=S(t),o=s.length;return r<0||r>=o?void 0:(n=s.charCodeAt(r))<55296||n>56319||r+1===o||(i=s.charCodeAt(r+1))<56320||i>57343?n:i-56320+(n-55296<<10)+65536});x(x.P,"String",{codePointAt:function(e){return A(this,e)}}),n.String.codePointAt;var k=Math.max,M=Math.min,F=String.fromCharCode,I=String.fromCodePoint;x(x.S+x.F*(!!I&&1!=I.length),"String",{fromCodePoint:function(e){for(var t,n=arguments,i=[],s=arguments.length,r=0;s>r;){if(t=+n[r++],a=1114111,((o=S(o=t))<0?k(o+a,0):M(o,a))!==t)throw RangeError(t+" is not a valid code point");i.push(t<65536?F(t):F(55296+((t-=65536)>>10),t%1024+56320))}var o,a;return i.join("")}}),n.String.fromCodePoint;var O,P,B,R,T,L,j,N,z,U,q,W,H,K,$={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u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3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60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uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},V={isSpaceSeparator:function(e){return"string"==typeof e&&$.Space_Separator.test(e)},isIdStartChar:function(e){return"string"==typeof e&&(e>="a"&&e<="z"||e>="A"&&e<="Z"||"$"===e||"_"===e||$.ID_Start.test(e))},isIdContinueChar:function(e){return"string"==typeof e&&(e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"$"===e||"_"===e||"‌"===e||"‍"===e||$.ID_Continue.test(e))},isDigit:function(e){return"string"==typeof e&&/[0-9]/.test(e)},isHexDigit:function(e){return"string"==typeof e&&/[0-9A-Fa-f]/.test(e)}};function J(e,t,n){var i=e[t];if(null!=i&&"object"==typeof i)if(Array.isArray(i))for(var s=0;s0;){var n=Y();if(!V.isHexDigit(n))throw re(X());e+=X()}return String.fromCodePoint(parseInt(e,16))}var ne={start:function(){if("eof"===j.type)throw oe();ie()},beforePropertyName:function(){switch(j.type){case"identifier":case"string":return N=j.value,void(P="afterPropertyName");case"punctuator":return void se();case"eof":throw oe()}},afterPropertyName:function(){if("eof"===j.type)throw oe();P="beforePropertyValue"},beforePropertyValue:function(){if("eof"===j.type)throw oe();ie()},beforeArrayValue:function(){if("eof"===j.type)throw oe();"punctuator"!==j.type||"]"!==j.value?ie():se()},afterPropertyValue:function(){if("eof"===j.type)throw oe();switch(j.value){case",":return void(P="beforePropertyName");case"}":se()}},afterArrayValue:function(){if("eof"===j.type)throw oe();switch(j.value){case",":return void(P="beforeArrayValue");case"]":se()}},end:function(){}};function ie(){var e;switch(j.type){case"punctuator":switch(j.value){case"{":e={};break;case"[":e=[]}break;case"null":case"boolean":case"numeric":case"string":e=j.value}if(void 0===z)z=e;else{var t=B[B.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,N,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(null!==e&&"object"==typeof e)B.push(e),P=Array.isArray(e)?"beforeArrayValue":"beforePropertyName";else{var n=B[B.length-1];P=null==n?"end":Array.isArray(n)?"afterArrayValue":"afterPropertyValue"}}function se(){B.pop();var e=B[B.length-1];P=null==e?"end":Array.isArray(e)?"afterArrayValue":"afterPropertyValue"}function re(e){return ce(void 0===e?"JSON5: invalid end of input at "+T+":"+L:"JSON5: invalid character '"+le(e)+"' at "+T+":"+L)}function oe(){return ce("JSON5: invalid end of input at "+T+":"+L)}function ae(){return ce("JSON5: invalid identifier character at "+T+":"+(L-=5))}function le(e){var t={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(t[e])return t[e];if(e<" "){var n=e.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return e}function ce(e){var t=new SyntaxError(e);return t.lineNumber=T,t.columnNumber=L,t}return{parse:function(e,t){O=String(e),P="start",B=[],R=0,T=1,L=0,j=void 0,N=void 0,z=void 0;do{j=G(),ne[P]()}while("eof"!==j.type);return"function"==typeof t?J({"":z},"",t):z},stringify:function(e,t,n){var i,s,r,o=[],a="",l="";if(null==t||"object"!=typeof t||Array.isArray(t)||(n=t.space,r=t.quote,t=t.replacer),"function"==typeof t)s=t;else if(Array.isArray(t)){i=[];for(var c=0,u=t;c0&&(n=Math.min(10,Math.floor(n)),l=" ".substr(0,n)):"string"==typeof n&&(l=n.substr(0,10)),p("",{"":e});function p(e,t){var n=t[e];switch(null!=n&&("function"==typeof n.toJSON5?n=n.toJSON5(e):"function"==typeof n.toJSON&&(n=n.toJSON(e))),s&&(n=s.call(t,e,n)),n instanceof Number?n=Number(n):n instanceof String?n=String(n):n instanceof Boolean&&(n=n.valueOf()),n){case null:return"null";case!0:return"true";case!1:return"false"}return"string"==typeof n?f(n):"number"==typeof n?String(n):"object"==typeof n?Array.isArray(n)?function(e){if(o.indexOf(e)>=0)throw TypeError("Converting circular structure to JSON5");o.push(e);var t=a;a+=l;for(var n,i=[],s=0;s=0)throw TypeError("Converting circular structure to JSON5");o.push(e);var t=a;a+=l;for(var n,s,r=[],c=0,u=i||Object.keys(e);c{e.exports=function e(t,n,i){function s(o,a){if(!n[o]){if(!t[o]){if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[o]={exports:{}};t[o][0].call(c.exports,(function(e){return s(t[o][1][e]||e)}),c,c.exports,e,t,n,i)}return n[o].exports}for(var r=void 0,o=0;o=43)}})).catch((function(){return!1}))}(e).then((function(e){return h=e}))}function y(e){var t=p[e.name],n={};n.promise=new o((function(e,t){n.resolve=e,n.reject=t})),t.deferredOperations.push(n),t.dbReady?t.dbReady=t.dbReady.then((function(){return n.promise})):t.dbReady=n.promise}function b(e){var t=p[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function w(e,t){var n=p[e.name].deferredOperations.pop();if(n)return n.reject(t),n.promise}function D(e,t){return new o((function(n,i){if(p[e.name]=p[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return n(e.db);y(e),e.db.close()}var r=[e.name];t&&r.push(e.version);var o=s.open.apply(s,r);t&&(o.onupgradeneeded=function(t){var n=o.result;try{n.createObjectStore(e.storeName),t.oldVersion<=1&&n.createObjectStore(d)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),o.onerror=function(e){e.preventDefault(),i(o.error)},o.onsuccess=function(){var t=o.result;t.onversionchange=function(e){e.target.close()},n(t),b(e)}}))}function x(e){return D(e,!1)}function C(e){return D(e,!0)}function E(e,t){if(!e.db)return!0;var n=!e.db.objectStoreNames.contains(e.storeName),i=e.versione.db.version;if(i&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),s||n){if(n){var r=e.db.version+1;r>e.version&&(e.version=r)}return!0}return!1}function S(e){return r([v(atob(e.data))],{type:e.type})}function A(e){return e&&e.__local_forage_encoded_blob}function k(e){var t=this,n=t._initReady().then((function(){var e=p[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady}));return l(n,e,e),n}function M(e,t,n,i){void 0===i&&(i=1);try{var s=e.db.transaction(e.storeName,t);n(null,s)}catch(s){if(i>0&&(!e.db||"InvalidStateError"===s.name||"NotFoundError"===s.name))return o.resolve().then((function(){if(!e.db||"NotFoundError"===s.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),C(e)})).then((function(){return function(e){y(e);for(var t=p[e.name],n=t.forages,i=0;i>4,u[l++]=(15&i)<<4|s>>2,u[l++]=(3&s)<<6|63&r;return c}function Y(e){var t,n=new Uint8Array(e),i="";for(t=0;t>2],i+=I[(3&n[t])<<4|n[t+1]>>4],i+=I[(15&n[t+1])<<2|n[t+2]>>6],i+=I[63&n[t+2]];return n.length%3==2?i=i.substring(0,i.length-1)+"=":n.length%3==1&&(i=i.substring(0,i.length-2)+"=="),i}var X={serialize:function(e,t){var n="";if(e&&(n=J.call(e)),e&&("[object ArrayBuffer]"===n||e.buffer&&"[object ArrayBuffer]"===J.call(e.buffer))){var i,s=B;e instanceof ArrayBuffer?(i=e,s+=T):(i=e.buffer,"[object Int8Array]"===n?s+=j:"[object Uint8Array]"===n?s+=N:"[object Uint8ClampedArray]"===n?s+=z:"[object Int16Array]"===n?s+=U:"[object Uint16Array]"===n?s+=W:"[object Int32Array]"===n?s+=q:"[object Uint32Array]"===n?s+=H:"[object Float32Array]"===n?s+=K:"[object Float64Array]"===n?s+=$:t(new Error("Failed to get type for BinaryArray"))),t(s+Y(i))}else if("[object Blob]"===n){var r=new FileReader;r.onload=function(){var n=O+e.type+"~"+Y(this.result);t(B+L+n)},r.readAsArrayBuffer(e)}else try{t(JSON.stringify(e))}catch(n){console.error("Couldn't convert value into a JSON string: ",e),t(null,n)}},deserialize:function(e){if(e.substring(0,R)!==B)return JSON.parse(e);var t,n=e.substring(V),i=e.substring(R,V);if(i===L&&P.test(n)){var s=n.match(P);t=s[1],n=n.substring(s[0].length)}var o=G(n);switch(i){case T:return o;case L:return r([o],{type:t});case j:return new Int8Array(o);case N:return new Uint8Array(o);case z:return new Uint8ClampedArray(o);case U:return new Int16Array(o);case W:return new Uint16Array(o);case q:return new Int32Array(o);case H:return new Uint32Array(o);case K:return new Float32Array(o);case $:return new Float64Array(o);default:throw new Error("Unkown type: "+i)}},stringToBuffer:G,bufferToString:Y};function Z(e,t,n,i){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,i)}function Q(e,t,n,i,s,r){e.executeSql(n,i,s,(function(e,o){o.code===o.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[t.storeName],(function(e,a){a.rows.length?r(e,o):Z(e,t,(function(){e.executeSql(n,i,s,r)}),r)}),r):r(e,o)}),r)}function ee(e,t,n,i){var s=this;e=c(e);var r=new o((function(r,o){s.ready().then((function(){void 0===t&&(t=null);var a=t,l=s._dbInfo;l.serializer.serialize(t,(function(t,c){c?o(c):l.db.transaction((function(n){Q(n,l,"INSERT OR REPLACE INTO "+l.storeName+" (key, value) VALUES (?, ?)",[e,t],(function(){r(a)}),(function(e,t){o(t)}))}),(function(t){if(t.code===t.QUOTA_ERR){if(i>0)return void r(ee.apply(s,[e,a,n,i-1]));o(t)}}))}))})).catch(o)}));return a(r,n),r}var te={_driver:"webSQLStorage",_initStorage:function(e){var t=this,n={db:null};if(e)for(var i in e)n[i]="string"!=typeof e[i]?e[i].toString():e[i];var s=new o((function(e,i){try{n.db=openDatabase(n.name,String(n.version),n.description,n.size)}catch(e){return i(e)}n.db.transaction((function(s){Z(s,n,(function(){t._dbInfo=n,e()}),(function(e,t){i(t)}))}),i)}));return n.serializer=X,s},_support:"function"==typeof openDatabase,iterate:function(e,t){var n=this,i=new o((function(t,i){n.ready().then((function(){var s=n._dbInfo;s.db.transaction((function(n){Q(n,s,"SELECT * FROM "+s.storeName,[],(function(n,i){for(var r=i.rows,o=r.length,a=0;a '__WebKitDatabaseInfoTable__'",[],(function(n,i){for(var s=[],r=0;r0}var se={_driver:"localStorageWrapper",_initStorage:function(e){var t={};if(e)for(var n in e)t[n]=e[n];return t.keyPrefix=ne(e,this._defaultConfig),ie()?(this._dbInfo=t,t.serializer=X,o.resolve()):o.reject()},_support:function(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&!!localStorage.setItem}catch(e){return!1}}(),iterate:function(e,t){var n=this,i=n.ready().then((function(){for(var t=n._dbInfo,i=t.keyPrefix,s=i.length,r=localStorage.length,o=1,a=0;a=0;n--){var i=localStorage.key(n);0===i.indexOf(e)&&localStorage.removeItem(i)}}));return a(n,e),n},length:function(e){var t=this.keys().then((function(e){return e.length}));return a(t,e),t},key:function(e,t){var n=this,i=n.ready().then((function(){var t,i=n._dbInfo;try{t=localStorage.key(e)}catch(e){t=null}return t&&(t=t.substring(i.keyPrefix.length)),t}));return a(i,t),i},keys:function(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo,n=localStorage.length,i=[],s=0;s=0;t--){var n=localStorage.key(t);0===n.indexOf(e)&&localStorage.removeItem(n)}})):o.reject("Invalid arguments"),a(i,t),i}},re=function(e,t){for(var n=e.length,i=0;i{"use strict";function t(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function n(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}e.exports=function(e,i){i||(i={});var s={bools:{},strings:{},unknownFn:null};"function"==typeof i.unknown&&(s.unknownFn=i.unknown),"boolean"==typeof i.boolean&&i.boolean?s.allBools=!0:[].concat(i.boolean).filter(Boolean).forEach((function(e){s.bools[e]=!0}));var r={};function o(e){return r[e].some((function(e){return s.bools[e]}))}Object.keys(i.alias||{}).forEach((function(e){r[e]=[].concat(i.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(i.string).filter(Boolean).forEach((function(e){s.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){s.strings[e]=!0}))}));var a=i.default||{},l={_:[]};function c(e,t,i){for(var r=e,o=0;o=2&&(n=n.slice(2)):v(s)?n=i[4]:s?r&&(n=n.slice(2)):a>=2&&v(t.protocol)&&(n=i[4]),{protocol:s,slashes:r||v(s),slashesCount:a,rest:n}}function y(e,t,n){if(e=(e=p(e)).replace(l,""),!(this instanceof y))return new y(e,t,n);var s,r,o,c,u,h,m=f.slice(),b=typeof t,w=this,D=0;for("object"!==b&&"string"!==b&&(n=t,t=null),n&&"function"!=typeof n&&(n=a.parse),s=!(r=_(e||"",t=g(t))).protocol&&!r.slashes,w.slashes=r.slashes||s&&t.slashes,w.protocol=r.protocol||t.protocol||"",e=r.rest,("file:"===r.protocol&&(2!==r.slashesCount||d.test(e))||!r.slashes&&(r.protocol||r.slashesCount<2||!v(w.protocol)))&&(m[3]=[/(.*)/,"pathname"]);D=0?e.slice(0,t):e}C.prototype.addEventListener=function(e,t){"function"==typeof t&&(Array.isArray(this.listeners[e])||(this.listeners[e]=[]),0===function(e,t){void 0===e&&(e=[]);var n=[];return e.forEach((function(e){t(e)&&n.push(e)})),n}(this.listeners[e],(function(e){return e===t})).length&&this.listeners[e].push(t))},C.prototype.removeEventListener=function(e,t){var n=this.listeners[e];this.listeners[e]=x(n,(function(e){return e===t}))},C.prototype.dispatchEvent=function(e){for(var t=this,n=[],i=arguments.length-1;i-- >0;)n[i]=arguments[i+1];var s=e.type,r=this.listeners[s];return!!Array.isArray(r)&&(r.forEach((function(i){n.length>0?i.apply(t,n):i.call(t,e)})),!0)};var S=function(){this.urlMap={}};S.prototype.attachWebSocket=function(e,t){var n=E(t),i=this.urlMap[n];if(i&&i.server&&-1===i.websockets.indexOf(e))return i.websockets.push(e),i.server},S.prototype.addMembershipToRoom=function(e,t){var n=this.urlMap[E(e.url)];n&&n.server&&-1!==n.websockets.indexOf(e)&&(n.roomMemberships[t]||(n.roomMemberships[t]=[]),n.roomMemberships[t].push(e))},S.prototype.attachServer=function(e,t){var n=E(t);if(!this.urlMap[n])return this.urlMap[n]={server:e,websockets:[],roomMemberships:{}},e},S.prototype.serverLookup=function(e){var t=E(e),n=this.urlMap[t];if(n)return n.server},S.prototype.websocketsLookup=function(e,t,n){var i,s=E(e),r=this.urlMap[s];return i=r?r.websockets:[],t&&(i=r.roomMemberships[t]||[]),n?i.filter((function(e){return e!==n})):i},S.prototype.removeServer=function(e){delete this.urlMap[E(e)]},S.prototype.removeWebSocket=function(e,t){var n=E(t),i=this.urlMap[n];i&&(i.websockets=x(i.websockets,(function(t){return t===e})))},S.prototype.removeMembershipFromRoom=function(e,t){var n=this.urlMap[E(e.url)],i=n.roomMemberships[t];n&&null!==i&&(n.roomMemberships[t]=x(i,(function(t){return t===e})))};var A=new S,k={CLOSE_NORMAL:1e3,CLOSE_GOING_AWAY:1001,CLOSE_PROTOCOL_ERROR:1002,CLOSE_UNSUPPORTED:1003,CLOSE_NO_STATUS:1005,CLOSE_ABNORMAL:1006,UNSUPPORTED_DATA:1007,POLICY_VIOLATION:1008,CLOSE_TOO_LARGE:1009,MISSING_EXTENSION:1010,INTERNAL_ERROR:1011,SERVICE_RESTART:1012,TRY_AGAIN_LATER:1013,TLS_HANDSHAKE:1015},M={CONSTRUCTOR_ERROR:"Failed to construct 'WebSocket':",CLOSE_ERROR:"Failed to execute 'close' on 'WebSocket':",EVENT:{CONSTRUCT:"Failed to construct 'Event':",MESSAGE:"Failed to construct 'MessageEvent':",CLOSE:"Failed to construct 'CloseEvent':"}},F=function(){};F.prototype.stopPropagation=function(){},F.prototype.stopImmediatePropagation=function(){},F.prototype.initEvent=function(e,t,n){void 0===e&&(e="undefined"),void 0===t&&(t=!1),void 0===n&&(n=!1),this.type=""+e,this.bubbles=Boolean(t),this.cancelable=Boolean(n)};var I=function(e){function t(t,n){if(void 0===n&&(n={}),e.call(this),!t)throw new TypeError(M.EVENT_ERROR+" 1 argument required, but only 0 present.");if("object"!=typeof n)throw new TypeError(M.EVENT_ERROR+" parameter 2 ('eventInitDict') is not an object.");var i=n.bubbles,s=n.cancelable;this.type=""+t,this.timeStamp=Date.now(),this.target=null,this.srcElement=null,this.returnValue=!0,this.isTrusted=!1,this.eventPhase=0,this.defaultPrevented=!1,this.currentTarget=null,this.cancelable=!!s&&Boolean(s),this.cancelBubble=!1,this.bubbles=!!i&&Boolean(i)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(F),O=function(e){function t(t,n){if(void 0===n&&(n={}),e.call(this),!t)throw new TypeError(M.EVENT.MESSAGE+" 1 argument required, but only 0 present.");if("object"!=typeof n)throw new TypeError(M.EVENT.MESSAGE+" parameter 2 ('eventInitDict') is not an object");var i=n.bubbles,s=n.cancelable,r=n.data,o=n.origin,a=n.lastEventId,l=n.ports;this.type=""+t,this.timeStamp=Date.now(),this.target=null,this.srcElement=null,this.returnValue=!0,this.isTrusted=!1,this.eventPhase=0,this.defaultPrevented=!1,this.currentTarget=null,this.cancelable=!!s&&Boolean(s),this.canncelBubble=!1,this.bubbles=!!i&&Boolean(i),this.origin=""+o,this.ports=void 0===l?null:l,this.data=void 0===r?null:r,this.lastEventId=""+(a||"")}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(F),P=function(e){function t(t,n){if(void 0===n&&(n={}),e.call(this),!t)throw new TypeError(M.EVENT.CLOSE+" 1 argument required, but only 0 present.");if("object"!=typeof n)throw new TypeError(M.EVENT.CLOSE+" parameter 2 ('eventInitDict') is not an object");var i=n.bubbles,s=n.cancelable,r=n.code,o=n.reason,a=n.wasClean;this.type=""+t,this.timeStamp=Date.now(),this.target=null,this.srcElement=null,this.returnValue=!0,this.isTrusted=!1,this.eventPhase=0,this.defaultPrevented=!1,this.currentTarget=null,this.cancelable=!!s&&Boolean(s),this.cancelBubble=!1,this.bubbles=!!i&&Boolean(i),this.code="number"==typeof r?parseInt(r,10):0,this.reason=""+(o||""),this.wasClean=!!a&&Boolean(a)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(F);function B(e){var t=e.type,n=e.target,i=new I(t);return n&&(i.target=n,i.srcElement=n,i.currentTarget=n),i}function R(e){var t=e.type,n=e.origin,i=e.data,s=e.target,r=new O(t,{data:i,origin:n});return s&&(r.target=s,r.srcElement=s,r.currentTarget=s),r}function T(e){var t=e.code,n=e.reason,i=e.type,s=e.target,r=e.wasClean;r||(r=t===k.CLOSE_NORMAL||t===k.CLOSE_NO_STATUS);var o=new P(i,{code:t,reason:n,wasClean:r});return s&&(o.target=s,o.srcElement=s,o.currentTarget=s),o}function L(e,t,n){e.readyState=U.CLOSING;var i=A.serverLookup(e.url),s=T({type:"close",target:e.target,code:t,reason:n});w((function(){A.removeWebSocket(e,e.url),e.readyState=U.CLOSED,e.dispatchEvent(s),i&&i.dispatchEvent(s,i)}),e)}function j(e){return"[object Blob]"===Object.prototype.toString.call(e)||e instanceof ArrayBuffer||(e=String(e)),e}var N=new WeakMap;function z(e){if(N.has(e))return N.get(e);var t=new Proxy(e,{get:function(n,i){if("close"===i)return function(e){void 0===e&&(e={});var n=e.code||k.CLOSE_NORMAL,i=e.reason||"";L(t,n,i)};if("send"===i)return function(t){t=j(t),e.dispatchEvent(R({type:"message",data:t,origin:this.url,target:e}))};var s=function(e){return"message"===e?"server::"+e:e};return"on"===i?function(t,n){e.addEventListener(s(t),n)}:"off"===i?function(t,n){e.removeEventListener(s(t),n)}:"target"===i?e:n[i]}});return N.set(e,t),t}var U=function(e){function t(n,i){e.call(this),this._onopen=null,this._onmessage=null,this._onerror=null,this._onclose=null,this.url=function(e){var t=new b(e),n=t.pathname,i=t.protocol,s=t.hash;if(!e)throw new TypeError(M.CONSTRUCTOR_ERROR+" 1 argument required, but only 0 present.");if(n||(t.pathname="/"),""===i)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The URL '"+t.toString()+"' is invalid.");if("ws:"!==i&&"wss:"!==i)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The URL's scheme must be either 'ws' or 'wss'. '"+i+"' is not allowed.");if(""!==s)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The URL contains a fragment identifier ('"+s+"'). Fragment identifiers are not allowed in WebSocket URLs.");return t.toString()}(n),i=function(e){if(void 0===e&&(e=[]),!Array.isArray(e)&&"string"!=typeof e)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The subprotocol '"+e.toString()+"' is invalid.");"string"==typeof e&&(e=[e]);var t=e.map((function(e){return{count:1,protocol:e}})).reduce((function(e,t){return e[t.protocol]=(e[t.protocol]||0)+t.count,e}),{}),n=Object.keys(t).filter((function(e){return t[e]>1}));if(n.length>0)throw new SyntaxError(M.CONSTRUCTOR_ERROR+" The subprotocol '"+n[0]+"' is duplicated.");return e}(i),this.protocol=i[0]||"",this.binaryType="blob",this.readyState=t.CONNECTING;var s=z(this),r=A.attachWebSocket(s,this.url);w((function(){if(r)if(r.options.verifyClient&&"function"==typeof r.options.verifyClient&&!r.options.verifyClient())this.readyState=t.CLOSED,D("error","WebSocket connection to '"+this.url+"' failed: HTTP Authentication failed; no valid credentials available"),A.removeWebSocket(s,this.url),this.dispatchEvent(B({type:"error",target:this})),this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL}));else{if(r.options.selectProtocol&&"function"==typeof r.options.selectProtocol){var e=r.options.selectProtocol(i),n=""!==e,o=-1!==i.indexOf(e);if(n&&!o)return this.readyState=t.CLOSED,D("error","WebSocket connection to '"+this.url+"' failed: Invalid Sub-Protocol"),A.removeWebSocket(s,this.url),this.dispatchEvent(B({type:"error",target:this})),void this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL}));this.protocol=e}this.readyState=t.OPEN,this.dispatchEvent(B({type:"open",target:this})),r.dispatchEvent(B({type:"connection"}),s)}else this.readyState=t.CLOSED,this.dispatchEvent(B({type:"error",target:this})),this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL})),D("error","WebSocket connection to '"+this.url+"' failed")}),this)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={onopen:{},onmessage:{},onclose:{},onerror:{}};return n.onopen.get=function(){return this._onopen},n.onmessage.get=function(){return this._onmessage},n.onclose.get=function(){return this._onclose},n.onerror.get=function(){return this._onerror},n.onopen.set=function(e){this.removeEventListener("open",this._onopen),this._onopen=e,this.addEventListener("open",e)},n.onmessage.set=function(e){this.removeEventListener("message",this._onmessage),this._onmessage=e,this.addEventListener("message",e)},n.onclose.set=function(e){this.removeEventListener("close",this._onclose),this._onclose=e,this.addEventListener("close",e)},n.onerror.set=function(e){this.removeEventListener("error",this._onerror),this._onerror=e,this.addEventListener("error",e)},t.prototype.send=function(e){var n=this;if(this.readyState===t.CLOSING||this.readyState===t.CLOSED)throw new Error("WebSocket is already in CLOSING or CLOSED state");var i=R({type:"server::message",origin:this.url,data:j(e)}),s=A.serverLookup(this.url);s&&w((function(){n.dispatchEvent(i,e)}),s)},t.prototype.close=function(e,n){if(void 0!==e&&("number"!=typeof e||1e3!==e&&(e<3e3||e>4999)))throw new TypeError(M.CLOSE_ERROR+" The code must be either 1000, or between 3000 and 4999. "+e+" is neither.");if(void 0!==n&&(i=n,s=encodeURIComponent(i).match(/%[89ABab]/g),i.length+(s?s.length:0)>123))throw new SyntaxError(M.CLOSE_ERROR+" The message must not be greater than 123 bytes.");var i,s;if(this.readyState!==t.CLOSING&&this.readyState!==t.CLOSED){var r=z(this);this.readyState===t.CONNECTING?function(e,t,n){e.readyState=U.CLOSING;var i=A.serverLookup(e.url),s=T({type:"close",target:e.target,code:t,reason:n,wasClean:!1}),r=B({type:"error",target:e.target});w((function(){A.removeWebSocket(e,e.url),e.readyState=U.CLOSED,e.dispatchEvent(r),e.dispatchEvent(s),i&&i.dispatchEvent(s,i)}),e)}(r,e||k.CLOSE_ABNORMAL,n):L(r,e||k.CLOSE_NO_STATUS,n)}},Object.defineProperties(t.prototype,n),t}(C);U.CONNECTING=0,U.prototype.CONNECTING=U.CONNECTING,U.OPEN=1,U.prototype.OPEN=U.OPEN,U.CLOSING=2,U.prototype.CLOSING=U.CLOSING,U.CLOSED=3,U.prototype.CLOSED=U.CLOSED;var q=function(e){function t(n,i){var s=this;void 0===n&&(n="socket.io"),void 0===i&&(i=""),e.call(this),this.binaryType="blob";var r=new b(n);r.pathname||(r.pathname="/"),this.url=r.toString(),this.readyState=t.CONNECTING,this.protocol="",this.target=this,"string"==typeof i||"object"==typeof i&&null!==i?this.protocol=i:Array.isArray(i)&&i.length>0&&(this.protocol=i[0]);var o=A.attachWebSocket(this,this.url);w((function(){o?(this.readyState=t.OPEN,o.dispatchEvent(B({type:"connection"}),o,this),o.dispatchEvent(B({type:"connect"}),o,this),this.dispatchEvent(B({type:"connect",target:this}))):(this.readyState=t.CLOSED,this.dispatchEvent(B({type:"error",target:this})),this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL})),D("error","Socket.io connection to '"+this.url+"' failed"))}),this),this.addEventListener("close",(function(e){s.dispatchEvent(T({type:"disconnect",target:e.target,code:e.code}))}))}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={broadcast:{}};return t.prototype.close=function(){if(this.readyState===t.OPEN){var e=A.serverLookup(this.url);return A.removeWebSocket(this,this.url),this.readyState=t.CLOSED,this.dispatchEvent(T({type:"close",target:this,code:k.CLOSE_NORMAL})),e&&e.dispatchEvent(T({type:"disconnect",target:this,code:k.CLOSE_NORMAL}),e),this}},t.prototype.disconnect=function(){return this.close()},t.prototype.emit=function(e){for(var n=[],i=arguments.length-1;i-- >0;)n[i]=arguments[i+1];if(this.readyState!==t.OPEN)throw new Error("SocketIO is already in CLOSING or CLOSED state");var s=R({type:e,origin:this.url,data:n}),r=A.serverLookup(this.url);return r&&r.dispatchEvent.apply(r,[s].concat(n)),this},t.prototype.send=function(e){return this.emit("message",e),this},n.broadcast.get=function(){if(this.readyState!==t.OPEN)throw new Error("SocketIO is already in CLOSING or CLOSED state");var e=this,n=A.serverLookup(this.url);if(!n)throw new Error("SocketIO can not find a server at the specified URL ("+this.url+")");return{emit:function(t,i){return n.emit(t,i,{websockets:A.websocketsLookup(e.url,null,e)}),e},to:function(t){return n.to(t,e)},in:function(t){return n.in(t,e)}}},t.prototype.on=function(e,t){return this.addEventListener(e,t),this},t.prototype.off=function(e,t){this.removeEventListener(e,t)},t.prototype.hasListeners=function(e){var t=this.listeners[e];return!!Array.isArray(t)&&!!t.length},t.prototype.join=function(e){A.addMembershipToRoom(this,e)},t.prototype.leave=function(e){A.removeMembershipFromRoom(this,e)},t.prototype.to=function(e){return this.broadcast.to(e)},t.prototype.in=function(){return this.to.apply(null,arguments)},t.prototype.dispatchEvent=function(e){for(var t=this,n=[],i=arguments.length-1;i-- >0;)n[i]=arguments[i+1];var s=e.type,r=this.listeners[s];if(!Array.isArray(r))return!1;r.forEach((function(i){n.length>0?i.apply(t,n):i.call(t,e.data?e.data:e)}))},Object.defineProperties(t.prototype,n),t}(C);q.CONNECTING=0,q.OPEN=1,q.CLOSING=2,q.CLOSED=3;var W=function(e,t){return new q(e,t)};W.connect=function(e,t){return W(e,t)};function H(){return"undefined"!=typeof window?window:"object"==typeof process&&"object"==typeof n.g?n.g:this}var K={mock:!0,verifyClient:null,selectProtocol:null},$=function(e){function t(t,n){void 0===n&&(n=K),e.call(this);var i=new b(t);if(i.pathname||(i.pathname="/"),this.url=i.toString(),this.originalWebSocket=null,!A.attachServer(this,this.url))throw this.dispatchEvent(B({type:"error"})),new Error("A mock server is already listening on this url");this.options=Object.assign({},K,n),this.options.mock&&this.mockWebsocket()}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.mockWebsocket=function(){var e=H();this.originalWebSocket=e.WebSocket,e.WebSocket=U},t.prototype.restoreWebsocket=function(){var e=H();null!==this.originalWebSocket&&(e.WebSocket=this.originalWebSocket),this.originalWebSocket=null},t.prototype.stop=function(e){void 0===e&&(e=function(){}),this.options.mock&&this.restoreWebsocket(),A.removeServer(this.url),"function"==typeof e&&e()},t.prototype.on=function(e,t){this.addEventListener(e,t)},t.prototype.off=function(e,t){this.removeEventListener(e,t)},t.prototype.close=function(e){void 0===e&&(e={});var t=e.code,n=e.reason,i=e.wasClean,s=A.websocketsLookup(this.url);A.removeServer(this.url),s.forEach((function(e){e.readyState=U.CLOSED,e.dispatchEvent(T({type:"close",target:e.target,code:t||k.CLOSE_NORMAL,reason:n||"",wasClean:i}))})),this.dispatchEvent(T({type:"close"}),this)},t.prototype.emit=function(e,t,n){var i=this;void 0===n&&(n={});var s,r=n.websockets;r||(r=A.websocketsLookup(this.url)),"object"!=typeof n||arguments.length>3?(t=Array.prototype.slice.call(arguments,1,arguments.length),s=t.map((function(e){return j(e)}))):s=j(t),r.forEach((function(n){var r=n instanceof q?t:s;Array.isArray(r)?n.dispatchEvent.apply(n,[R({type:e,data:r,origin:i.url,target:n.target})].concat(r)):n.dispatchEvent(R({type:e,data:r,origin:i.url,target:n.target}))}))},t.prototype.clients=function(){return A.websocketsLookup(this.url)},t.prototype.to=function(e,t,n){var i=this;void 0===n&&(n=[]);var s=this,r=n.concat(A.websocketsLookup(this.url,e,t)).reduce((function(e,t){return e.indexOf(t)>-1?e:e.concat(t)}),[]);return{to:function(e,t){return i.to.call(i,e,t,r)},emit:function(e,t){s.emit(e,t,{websockets:r})}}},t.prototype.in=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];return this.to.apply(null,e)},t.prototype.simulate=function(e){var t=A.websocketsLookup(this.url);"error"===e&&t.forEach((function(e){e.readyState=U.CLOSED,e.dispatchEvent(B({type:"error",target:e.target}))}))},t}(C);$.of=function(e){return new $(e)};var V=$,J=U,G=W;e.Server=V,e.WebSocket=J,e.SocketIO=G,Object.defineProperty(e,"__esModule",{value:!0})}(t)},1023:e=>{"use strict";function t(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function n(e,t){for(var n,i="",s=0,r=-1,o=0,a=0;a<=e.length;++a){if(a2){var l=i.lastIndexOf("/");if(l!==i.length-1){-1===l?(i="",s=0):s=(i=i.slice(0,l)).length-1-i.lastIndexOf("/"),r=a,o=0;continue}}else if(2===i.length||1===i.length){i="",s=0,r=a,o=0;continue}t&&(i.length>0?i+="/..":i="..",s=2)}else i.length>0?i+="/"+e.slice(r+1,a):i=e.slice(r+1,a),s=a-r-1;r=a,o=0}else 46===n&&-1!==o?++o:o=-1}return i}var i={resolve:function(){for(var e,i="",s=!1,r=arguments.length-1;r>=-1&&!s;r--){var o;r>=0?o=arguments[r]:(void 0===e&&(e=process.cwd()),o=e),t(o),0!==o.length&&(i=o+"/"+i,s=47===o.charCodeAt(0))}return i=n(i,!s),s?i.length>0?"/"+i:"/":i.length>0?i:"."},normalize:function(e){if(t(e),0===e.length)return".";var i=47===e.charCodeAt(0),s=47===e.charCodeAt(e.length-1);return 0!==(e=n(e,!i)).length||i||(e="."),e.length>0&&s&&(e+="/"),i?"/"+e:e},isAbsolute:function(e){return t(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,n=0;n0&&(void 0===e?e=s:e+="/"+s)}return void 0===e?".":i.normalize(e)},relative:function(e,n){if(t(e),t(n),e===n)return"";if((e=i.resolve(e))===(n=i.resolve(n)))return"";for(var s=1;sc){if(47===n.charCodeAt(a+d))return n.slice(a+d+1);if(0===d)return n.slice(a+d)}else o>c&&(47===e.charCodeAt(s+d)?u=d:0===d&&(u=0));break}var h=e.charCodeAt(s+d);if(h!==n.charCodeAt(a+d))break;47===h&&(u=d)}var p="";for(d=s+u+1;d<=r;++d)d!==r&&47!==e.charCodeAt(d)||(0===p.length?p+="..":p+="/..");return p.length>0?p+n.slice(a+u):(a+=u,47===n.charCodeAt(a)&&++a,n.slice(a))},_makeLong:function(e){return e},dirname:function(e){if(t(e),0===e.length)return".";for(var n=e.charCodeAt(0),i=47===n,s=-1,r=!0,o=e.length-1;o>=1;--o)if(47===(n=e.charCodeAt(o))){if(!r){s=o;break}}else r=!1;return-1===s?i?"/":".":i&&1===s?"//":e.slice(0,s)},basename:function(e,n){if(void 0!==n&&"string"!=typeof n)throw new TypeError('"ext" argument must be a string');t(e);var i,s=0,r=-1,o=!0;if(void 0!==n&&n.length>0&&n.length<=e.length){if(n.length===e.length&&n===e)return"";var a=n.length-1,l=-1;for(i=e.length-1;i>=0;--i){var c=e.charCodeAt(i);if(47===c){if(!o){s=i+1;break}}else-1===l&&(o=!1,l=i+1),a>=0&&(c===n.charCodeAt(a)?-1==--a&&(r=i):(a=-1,r=l))}return s===r?r=l:-1===r&&(r=e.length),e.slice(s,r)}for(i=e.length-1;i>=0;--i)if(47===e.charCodeAt(i)){if(!o){s=i+1;break}}else-1===r&&(o=!1,r=i+1);return-1===r?"":e.slice(s,r)},extname:function(e){t(e);for(var n=-1,i=0,s=-1,r=!0,o=0,a=e.length-1;a>=0;--a){var l=e.charCodeAt(a);if(47!==l)-1===s&&(r=!1,s=a+1),46===l?-1===n?n=a:1!==o&&(o=1):-1!==n&&(o=-1);else if(!r){i=a+1;break}}return-1===n||-1===s||0===o||1===o&&n===s-1&&n===i+1?"":e.slice(n,s)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var n=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return n?n===t.root?n+i:n+"/"+i:i}(0,e)},parse:function(e){t(e);var n={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return n;var i,s=e.charCodeAt(0),r=47===s;r?(n.root="/",i=1):i=0;for(var o=-1,a=0,l=-1,c=!0,u=e.length-1,d=0;u>=i;--u)if(47!==(s=e.charCodeAt(u)))-1===l&&(c=!1,l=u+1),46===s?-1===o?o=u:1!==d&&(d=1):-1!==o&&(d=-1);else if(!c){a=u+1;break}return-1===o||-1===l||0===d||1===d&&o===l-1&&o===a+1?-1!==l&&(n.base=n.name=0===a&&r?e.slice(1,l):e.slice(a,l)):(0===a&&r?(n.name=e.slice(1,o),n.base=e.slice(1,l)):(n.name=e.slice(a,o),n.base=e.slice(a,l)),n.ext=e.slice(o,l)),a>0?n.dir=e.slice(0,a-1):r&&(n.dir="/"),n},sep:"/",delimiter:":",win32:null,posix:null};i.posix=i,e.exports=i},7375:(e,t)=>{"use strict";var n=Object.prototype.hasOwnProperty;function i(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function s(e){try{return encodeURIComponent(e)}catch(e){return null}}t.stringify=function(e,t){t=t||"";var i,r,o=[];for(r in"string"!=typeof t&&(t="?"),e)if(n.call(e,r)){if((i=e[r])||null!=i&&!isNaN(i)||(i=""),r=s(r),i=s(i),null===r||null===i)continue;o.push(r+"="+i)}return o.length?t+o.join("&"):""},t.parse=function(e){for(var t,n=/([^=?#&]+)=?([^&]*)/g,s={};t=n.exec(e);){var r=i(t[1]),o=i(t[2]);null===r||null===o||r in s||(s[r]=o)}return s}},7245:e=>{"use strict";e.exports=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}},1920:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.setupThebeLite=t.startJupyterLiteServer=void 0;const i=n(5163),s=n(315);function r(){var e;window.thebeLite=Object.assign(null!==(e=window.thebeLite)&&void 0!==e?e:{},{startJupyterLiteServer:s.startJupyterLiteServer})}Object.defineProperty(t,"startJupyterLiteServer",{enumerable:!0,get:function(){return s.startJupyterLiteServer}}),t.setupThebeLite=r,"undefined"!=typeof window&&(console.debug("window is defined, setting up thebe-lite"),r(),console.debug("window.thebeLite",window.thebeLite)),i.__exportStar(n(3173),t)},315:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.startJupyterLiteServer=void 0;const i=n(5163),s=n(9622),r=n(3800),o=[Promise.resolve().then((()=>i.__importStar(n(9671))))];function*a(e){let t;t=Object.prototype.hasOwnProperty.call(e,"__esModule")?e.default:e;const n=Array.isArray(t)?t:[t];for(const e of n)yield e}t.startJupyterLiteServer=function(e){return i.__awaiter(this,void 0,void 0,(function*(){s.PageConfig.getOption(""),(null==e?void 0:e.litePluginSettings)&&s.PageConfig.setOption("litePluginSettings",JSON.stringify(e.litePluginSettings));const t=[];(yield Promise.all(o)).forEach((e=>{for(const n of a(e))t.push(n)}));const l=[Promise.resolve().then((()=>i.__importStar(n(4957))))];[].forEach((e=>{e.liteExtension&&l.push(function(e,t){return i.__awaiter(this,void 0,void 0,(function*(){try{return(yield window._JUPYTERLAB[e].get(t))()}catch(n){throw console.warn(`Failed to create module: package: ${e}; module: ${t}`),n}}))}(e.name,e.extension))})),(yield Promise.allSettled(l)).forEach((e=>{if("fulfilled"===e.status)for(const n of a(e.value))t.push(n);else console.error(e.reason)}));const c=new r.JupyterLiteServer({});c.registerPluginModules(t),yield c.start();const{serviceManager:u}=c;return yield u.ready,u}))}},3173:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},5163:(e,t,n)=>{"use strict";n.r(t),n.d(t,{__assign:()=>r,__asyncDelegator:()=>w,__asyncGenerator:()=>b,__asyncValues:()=>D,__await:()=>y,__awaiter:()=>u,__classPrivateFieldGet:()=>A,__classPrivateFieldSet:()=>k,__createBinding:()=>h,__decorate:()=>a,__exportStar:()=>p,__extends:()=>s,__generator:()=>d,__importDefault:()=>S,__importStar:()=>E,__makeTemplateObject:()=>x,__metadata:()=>c,__param:()=>l,__read:()=>m,__rest:()=>o,__spread:()=>g,__spreadArray:()=>_,__spreadArrays:()=>v,__values:()=>f});var i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},i(e,t)};function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var r=function(){return r=Object.assign||function(e){for(var t,n=1,i=arguments.length;n=0;a--)(s=e[a])&&(o=(r<3?s(o):r>3?s(t,n,o):s(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o}function l(e,t){return function(n,i){t(n,i,e)}}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function u(e,t,n,i){return new(n||(n=Promise))((function(s,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((i=i.apply(e,t||[])).next())}))}function d(e,t){var n,i,s,r,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return r={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function a(r){return function(a){return function(r){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,i&&(s=2&r[0]?i.return:r[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,r[1])).done)return s;switch(i=0,s&&(r=[2&r[0],s.value]),r[0]){case 0:case 1:s=r;break;case 4:return o.label++,{value:r[1],done:!1};case 5:o.label++,i=r[1],r=[0];continue;case 7:r=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==r[0]&&2!==r[0])){o=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,s,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function g(){for(var e=[],t=0;t1||a(e,t)}))})}function a(e,t){try{(n=s[e](t)).value instanceof y?Promise.resolve(n.value.v).then(l,c):u(r[0][2],n)}catch(e){u(r[0][3],e)}var n}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),r.shift(),r.length&&a(r[0][0],r[0][1])}}function w(e){var t,n;return t={},i("next"),i("throw",(function(e){throw e})),i("return"),t[Symbol.iterator]=function(){return this},t;function i(i,s){t[i]=e[i]?function(t){return(n=!n)?{value:y(e[i](t)),done:"return"===i}:s?s(t):t}:s}}function D(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=f(e),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise((function(i,s){!function(e,t,n,i){Promise.resolve(i).then((function(t){e({value:t,done:n})}),t)}(i,s,(t=e[n](t)).done,t.value)}))}}}function x(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var C=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};function E(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&h(t,e,n);return C(t,e),t}function S(e){return e&&e.__esModule?e:{default:e}}function A(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function k(e,t,n,i,s){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?s.call(e,n):s?s.value=n:t.set(e,n),n}},4846:(e,t,n)=>{"use strict";var i=n(7245),s=n(7375),r=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,o=/[\n\r\t]/g,a=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,l=/:\d+$/,c=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,u=/^[a-zA-Z]:/;function d(e){return(e||"").toString().replace(r,"")}var h=[["#","hash"],["?","query"],function(e,t){return m(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],p={hash:1,query:1};function f(e){var t,i=("undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{}).location||{},s={},r=typeof(e=e||i);if("blob:"===e.protocol)s=new v(unescape(e.pathname),{});else if("string"===r)for(t in s=new v(e,{}),p)delete s[t];else if("object"===r){for(t in e)t in p||(s[t]=e[t]);void 0===s.slashes&&(s.slashes=a.test(e.href))}return s}function m(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function g(e,t){e=(e=d(e)).replace(o,""),t=t||{};var n,i=c.exec(e),s=i[1]?i[1].toLowerCase():"",r=!!i[2],a=!!i[3],l=0;return r?a?(n=i[2]+i[3]+i[4],l=i[2].length+i[3].length):(n=i[2]+i[4],l=i[2].length):a?(n=i[3]+i[4],l=i[3].length):n=i[4],"file:"===s?l>=2&&(n=n.slice(2)):m(s)?n=i[4]:s?r&&(n=n.slice(2)):l>=2&&m(t.protocol)&&(n=i[4]),{protocol:s,slashes:r||m(s),slashesCount:l,rest:n}}function v(e,t,n){if(e=(e=d(e)).replace(o,""),!(this instanceof v))return new v(e,t,n);var r,a,l,c,p,_,y=h.slice(),b=typeof t,w=this,D=0;for("object"!==b&&"string"!==b&&(n=t,t=null),n&&"function"!=typeof n&&(n=s.parse),r=!(a=g(e||"",t=f(t))).protocol&&!a.slashes,w.slashes=a.slashes||r&&t.slashes,w.protocol=a.protocol||t.protocol||"",e=a.rest,("file:"===a.protocol&&(2!==a.slashesCount||u.test(e))||!a.slashes&&(a.protocol||a.slashesCount<2||!m(w.protocol)))&&(y[3]=[/(.*)/,"pathname"]);D{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ActivityMonitor=void 0;const i=n(4016);t.ActivityMonitor=class{constructor(e){this._timer=-1,this._timeout=-1,this._isDisposed=!1,this._activityStopped=new i.Signal(this),e.signal.connect(this._onSignalFired,this),this._timeout=e.timeout||1e3}get activityStopped(){return this._activityStopped}get timeout(){return this._timeout}set timeout(e){this._timeout=e}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,i.Signal.clearData(this))}_onSignalFired(e,t){clearTimeout(this._timer),this._sender=e,this._args=t,this._timer=setTimeout((()=>{this._activityStopped.emit({sender:this._sender,args:this._args})}),this._timeout)}}},9622:function(e,t,n){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(7542),t),s(n(2086),t),s(n(7390),t),s(n(9458),t),s(n(176),t),s(n(2643),t),s(n(7846),t),s(n(2533),t),s(n(7319),t)},2086:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},7390:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MarkdownCodeBlocks=void 0,function(e){e.CODE_BLOCK_MARKER="```";const t=[".markdown",".mdown",".mkdn",".md",".mkd",".mdwn",".mdtxt",".mdtext",".text",".txt",".Rmd"];class n{constructor(e){this.startLine=e,this.code="",this.endLine=-1}}e.MarkdownCodeBlock=n,e.isMarkdown=function(e){return t.indexOf(e)>-1},e.findMarkdownCodeBlocks=function(t){if(!t||""===t)return[];const i=t.split("\n"),s=[];let r=null;for(let t=0;te===t||i&&e===i))},e.isDisabled=function(t){const n=t.indexOf(":");let i="";return-1!==n&&(i=t.slice(0,n)),e.disabled.some((e=>e===t||i&&e===i))}}(Extension=PageConfig.Extension||(PageConfig.Extension={}))})(PageConfig=exports.PageConfig||(exports.PageConfig={}))},176:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PathExt=void 0;const i=n(1023);!function(e){function t(e){return 0===e.indexOf("/")&&(e=e.slice(1)),e}e.join=function(...e){const n=i.posix.join(...e);return"."===n?"":t(n)},e.basename=function(e,t){return i.posix.basename(e,t)},e.dirname=function(e){const n=t(i.posix.dirname(e));return"."===n?"":n},e.extname=function(e){return i.posix.extname(e)},e.normalize=function(e){return""===e?"":t(i.posix.normalize(e))},e.resolve=function(...e){return t(i.posix.resolve(...e))},e.relative=function(e,n){return t(i.posix.relative(e,n))},e.normalizeExtension=function(e){return e.length>0&&0!==e.indexOf(".")&&(e=`.${e}`),e},e.removeSlash=t}(t.PathExt||(t.PathExt={}))},2643:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.signalToPromise=void 0;const i=n(5082);t.signalToPromise=function(e,t){const n=new i.PromiseDelegate;function s(){e.disconnect(r)}function r(e,t){s(),n.resolve([e,t])}return e.connect(r),(null!=t?t:0)>0&&setTimeout((()=>{s(),n.reject(`Signal not emitted within ${t} ms.`)}),t),n.promise}},7846:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Text=void 0,function(e){const t="𝐚".length>1;e.jsIndexToCharIndex=function(e,n){if(t)return e;let i=e;for(let t=0;t+1=55296&&e<=56319){const e=n.charCodeAt(t+1);e>=56320&&e<=57343&&(i--,t++)}}return i},e.charIndexToJsIndex=function(e,n){if(t)return e;let i=e;for(let e=0;e+1=55296&&t<=56319){const t=n.charCodeAt(e+1);t>=56320&&t<=57343&&(i++,e++)}}return i},e.camelCase=function(e,t=!1){return e.replace(/^(\w)|[\s-_:]+(\w)/g,(function(e,n,i){return i?i.toUpperCase():t?n.toUpperCase():n.toLowerCase()}))},e.titleCase=function(e){return(e||"").toLowerCase().split(" ").map((e=>e.charAt(0).toUpperCase()+e.slice(1))).join(" ")}}(t.Text||(t.Text={}))},2533:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Time=void 0;const n=[{name:"years",milliseconds:31536e6},{name:"months",milliseconds:2592e6},{name:"days",milliseconds:864e5},{name:"hours",milliseconds:36e5},{name:"minutes",milliseconds:6e4},{name:"seconds",milliseconds:1e3}];var i;(i=t.Time||(t.Time={})).formatHuman=function(e){const t=document.documentElement.lang||"en",i=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),s=new Date(e).getTime()-Date.now();for(let e of n){const t=Math.ceil(s/e.milliseconds);if(0!==t)return i.format(t,e.name)}return i.format(0,"seconds")},i.format=function(e){const t=document.documentElement.lang||"en";return new Intl.DateTimeFormat(t,{dateStyle:"short",timeStyle:"short"}).format(new Date(e))}},7319:function(e,t,n){"use strict";var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.URLExt=void 0;const s=n(1023),r=i(n(4846));!function(e){function t(e){if("undefined"!=typeof document&&document){const t=document.createElement("a");return t.href=e,t}return(0,r.default)(e)}function n(...e){let t=(0,r.default)(e[0],{});const n=""===t.protocol&&t.slashes;n&&(t=(0,r.default)(e[0],"https:"+e[0]));const i=`${n?"":t.protocol}${t.slashes?"//":""}${t.auth}${t.auth?"@":""}${t.host}`,o=s.posix.join(`${i&&"/"!==t.pathname[0]?"/":""}${t.pathname}`,...e.slice(1));return`${i}${"."===o?"":o}`}e.parse=t,e.getHostName=function(e){return(0,r.default)(e).hostname},e.normalize=function(e){return e&&t(e).toString()},e.join=n,e.encodeParts=function(e){return n(...e.split("/").map(encodeURIComponent))},e.objectToQueryString=function(e){const t=Object.keys(e).filter((e=>e.length>0));return t.length?"?"+t.map((t=>{const n=encodeURIComponent(String(e[t]));return t+(n?"="+n:"")})).join("&"):""},e.queryStringToObject=function(e){return e.replace(/^\?/,"").split("&").reduce(((e,t)=>{const[n,i]=t.split("=");return n.length>0&&(e[n]=decodeURIComponent(i||"")),e}),{})},e.isLocal=function(e){const{protocol:n}=t(e);return(!n||0!==e.toLowerCase().indexOf(n))&&0!==e.indexOf("/")}}(t.URLExt||(t.URLExt={}))},5182:(e,t,n)=>{"use strict";n.d(t,{HB:()=>c,Hv:()=>a,dC:()=>u,vJ:()=>l});var i=n(9622),s=n(3893),r=n.n(s),o=n(5082);const a=new o.Token("@jupyterlite/contents:IContents");var l,c;!function(e){e.JSON="application/json",e.PLAIN_TEXT="text/plain",e.OCTET_STREAM="octet/stream"}(l||(l={})),function(e){const t=JSON.parse(i.PageConfig.getOption("fileTypes")||"{}");e.getType=function(e,n=null){e=e.toLowerCase();for(const n of Object.values(t))for(const t of n.extensions||[])if(t===e&&n.mimeTypes&&n.mimeTypes.length)return n.mimeTypes[0];return r().getType(e)||n||l.OCTET_STREAM},e.hasFormat=function(e,n){e=e.toLowerCase();for(const i of Object.values(t))if(i.fileFormat===n)for(const t of i.extensions||[])if(t===e)return!0;return!1}}(c||(c={}));const u=new o.Token("@jupyterlite/contents:IBroadcastChannelWrapper")},9842:(e,t,n)=>{"use strict";n.d(t,{Ll:()=>s,qP:()=>o,vM:()=>r});var i=n(5082);const s=new i.Token("@jupyterlite/kernel:IKernels"),r="javascript",o=new i.Token("@jupyterlite/kernel:IKernelSpecs")},4957:(e,t,n)=>{"use strict";n.r(t),n.d(t,{KERNEL_SETTINGS_SCHEMA:()=>l,default:()=>h});var i=n(9622),s=n(4374),r=n(9842),o=n(5182);const a=JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema","$id":"https://jupyterlite-pyodide-kernel.readthedocs.org/en/latest/reference/schema/settings-v0.html#","title":"Pyodide Kernel Settings Schema v0","description":"Pyodide-specific configuration values. Will be defined in another location in the future.","type":"object","properties":{"pyodideUrl":{"description":"The path to the main pyodide.js entry point","type":"string","default":"https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js","format":"uri"},"disablePyPIFallback":{"description":"Disable the piplite behavior of falling back to https://pypi.org/pypi/","default":false,"type":"boolean"},"pipliteUrls":{"description":"Paths to PyPI-compatible API endpoints for wheels. If ending in ``all.json``, assumed to be an aggregate, keyed by package name, with relative paths","type":"array","items":{"type":"string"},"default":[],"format":"uri"}}}');var l=n.t(a,2),c=n(1173);const u=`data:image/svg+xml;base64,${btoa(n.n(c)())}`,d="@jupyterlite/pyodide-kernel-extension:kernel",h=[{id:d,autoStart:!0,requires:[r.qP],optional:[s.f,o.dC],activate:(e,t,s,r)=>{const o=JSON.parse(i.PageConfig.getOption("litePluginSettings")||"{}")[d]||{},a=o.pyodideUrl||"https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js",l=i.URLExt.parse(a).href,c=o.pipliteWheelUrl?i.URLExt.parse(o.pipliteWheelUrl).href:void 0,h=(o.pipliteUrls||[]).map((e=>i.URLExt.parse(e).href)),p=!!o.disablePyPIFallback;t.register({spec:{name:"python",display_name:"Python (Pyodide)",language:"python",argv:[],resources:{"logo-32x32":u,"logo-64x64":u}},create:async e=>{const{PyodideKernel:t}=await Promise.all([n.e(296),n.e(510)]).then(n.bind(n,144)),i=!(!(null==s?void 0:s.enabled)||!(null==r?void 0:r.enabled));return i?console.info("Pyodide contents will be synced with Jupyter Contents"):console.warn("Pyodide contents will NOT be synced with Jupyter Contents"),new t({...e,pyodideUrl:l,pipliteWheelUrl:c,pipliteUrls:h,disablePyPIFallback:p,mountDrive:i})}})}}]},9671:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>Q});var i=n(9622),s=n(5182),r=n(5082);const o="JupyterLite Storage";class a{constructor(e){this.reduceBytesToString=(e,t)=>e+String.fromCharCode(t),this._serverContents=new Map,this._storageName=o,this._storageDrivers=null,this._localforage=e.localforage,this._storageName=e.storageName||o,this._storageDrivers=e.storageDrivers||null,this._ready=new r.PromiseDelegate}async initialize(){await this.initStorage(),this._ready.resolve(void 0)}async initStorage(){this._storage=this.createDefaultStorage(),this._counters=this.createDefaultCounters(),this._checkpoints=this.createDefaultCheckpoints()}get ready(){return this._ready.promise}get storage(){return this.ready.then((()=>this._storage))}get counters(){return this.ready.then((()=>this._counters))}get checkpoints(){return this.ready.then((()=>this._checkpoints))}get defaultStorageOptions(){const e=this._storageDrivers&&this._storageDrivers.length?this._storageDrivers:null;return{version:1,name:this._storageName,...e?{driver:e}:{}}}createDefaultStorage(){return this._localforage.createInstance({description:"Offline Storage for Notebooks and Files",storeName:"files",...this.defaultStorageOptions})}createDefaultCounters(){return this._localforage.createInstance({description:"Store the current file suffix counters",storeName:"counters",...this.defaultStorageOptions})}createDefaultCheckpoints(){return this._localforage.createInstance({description:"Offline Storage for Checkpoints",storeName:"checkpoints",...this.defaultStorageOptions})}async newUntitled(e){var t,n,r;const o=null!==(t=null==e?void 0:e.path)&&void 0!==t?t:"",a=null!==(n=null==e?void 0:e.type)&&void 0!==n?n:"notebook",c=(new Date).toISOString();let u=i.PathExt.dirname(o);const d=i.PathExt.basename(o),h=i.PathExt.extname(o),p=await this.get(u);let f,m="";switch(o&&!h&&p?(u=`${o}/`,m=""):u&&d?(u=`${u}/`,m=d):(u="",m=o),a){case"directory":m=`Untitled Folder${await this._incrementCounter("directory")||""}`,f={name:m,path:`${u}${m}`,last_modified:c,created:c,format:"json",mimetype:"",content:null,size:0,writable:!0,type:"directory"};break;case"notebook":{const e=await this._incrementCounter("notebook");m=m||`Untitled${e||""}.ipynb`,f={name:m,path:`${u}${m}`,last_modified:c,created:c,format:"json",mimetype:s.vJ.JSON,content:l.EMPTY_NB,size:JSON.stringify(l.EMPTY_NB).length,writable:!0,type:"notebook"};break}default:{const t=null!==(r=null==e?void 0:e.ext)&&void 0!==r?r:".txt",n=await this._incrementCounter("file"),i=s.HB.getType(t)||s.vJ.OCTET_STREAM;let o;o=s.HB.hasFormat(t,"text")||-1!==i.indexOf("text")?"text":-1!==t.indexOf("json")||-1!==t.indexOf("ipynb")?"json":"base64",m=m||`untitled${n||""}${t}`,f={name:m,path:`${u}${m}`,last_modified:c,created:c,format:o,mimetype:i,content:"",size:0,writable:!0,type:"file"};break}}const g=f.path;return await(await this.storage).setItem(g,f),f}async copy(e,t){let n=i.PathExt.basename(e);for(t=""===t?"":`${t.slice(1)}/`;await this.get(`${t}${n}`,{content:!0});){const e=i.PathExt.extname(n),t=n.replace(e,"");n=`${t} (copy)${e}`}const s=`${t}${n}`;let r=await this.get(e,{content:!0});if(!r)throw Error(`Could not find file with path ${e}`);return r={...r,name:n,path:s},await(await this.storage).setItem(s,r),r}async get(e,t){if(""===(e=decodeURIComponent(e.replace(/^\//,""))))return await this._getFolder(e);const n=await this.storage,r=await n.getItem(e),o=await this._getServerContents(e,t),a=r||o;if(!a)return null;if(!(null==t?void 0:t.content))return{size:0,...a,content:null};if("directory"===a.type){const t=new Map;await n.iterate(((n,i)=>{i===`${e}/${n.name}`&&t.set(n.name,n)}));const r=o?o.content:Array.from((await this._getServerDirectory(e)).values());for(const e of r)t.has(e.name)||t.set(e.name,e);const l=[...t.values()];return{name:i.PathExt.basename(e),path:e,last_modified:a.last_modified,created:a.created,format:"json",mimetype:s.vJ.JSON,content:l,size:0,writable:!0,type:"directory"}}return a}async rename(e,t){const n=decodeURIComponent(e),s=await this.get(n,{content:!0});if(!s)throw Error(`Could not find file with path ${n}`);const r=(new Date).toISOString(),o=i.PathExt.basename(t),a={...s,name:o,path:t,last_modified:r},l=await this.storage;if(await l.setItem(t,a),await l.removeItem(n),await(await this.checkpoints).removeItem(n),"directory"===s.type){let n;for(n of s.content)await this.rename(i.URLExt.join(e,n.name),i.URLExt.join(t,n.name))}return a}async save(e,t={}){var n;e=decodeURIComponent(e);const r=i.PathExt.extname(null!==(n=t.name)&&void 0!==n?n:""),o=t.chunk,a=!!o&&(o>1||-1===o);let l=await this.get(e,{content:a});if(l||(l=await this.newUntitled({path:e,ext:r,type:"file"})),!l)return null;const c=l.content,u=(new Date).toISOString();if(l={...l,...t,last_modified:u},t.content&&"base64"===t.format){const e=!o||-1===o;if(".ipynb"===r){const n=this._handleChunk(t.content,c,a);l={...l,content:e?JSON.parse(n):n,format:"json",type:"notebook",size:n.length}}else if(s.HB.hasFormat(r,"json")){const n=this._handleChunk(t.content,c,a);l={...l,content:e?JSON.parse(n):n,format:"json",type:"file",size:n.length}}else if(s.HB.hasFormat(r,"text")){const e=this._handleChunk(t.content,c,a);l={...l,content:e,format:"text",type:"file",size:e.length}}else{const e=t.content;l={...l,content:e,size:atob(e).length}}}return await(await this.storage).setItem(e,l),l}async delete(e){const t=`${e=decodeURIComponent(e)}/`,n=(await(await this.storage).keys()).filter((n=>n===e||n.startsWith(t)));await Promise.all(n.map(this.forgetPath,this))}async forgetPath(e){await Promise.all([(await this.storage).removeItem(e),(await this.checkpoints).removeItem(e)])}async createCheckpoint(e){var t;const n=await this.checkpoints;e=decodeURIComponent(e);const i=await this.get(e,{content:!0});if(!i)throw Error(`Could not find file with path ${e}`);const s=(null!==(t=await n.getItem(e))&&void 0!==t?t:[]).filter(Boolean);return s.push(i),s.length>5&&s.splice(0,s.length-5),await n.setItem(e,s),{id:""+(s.length-1),last_modified:i.last_modified}}async listCheckpoints(e){return(await(await this.checkpoints).getItem(e)||[]).filter(Boolean).map(this.normalizeCheckpoint,this)}normalizeCheckpoint(e,t){return{id:t.toString(),last_modified:e.last_modified}}async restoreCheckpoint(e,t){e=decodeURIComponent(e);const n=(await(await this.checkpoints).getItem(e)||[])[parseInt(t)];await(await this.storage).setItem(e,n)}async deleteCheckpoint(e,t){e=decodeURIComponent(e);const n=await(await this.checkpoints).getItem(e)||[],i=parseInt(t);n.splice(i,1),await(await this.checkpoints).setItem(e,n)}_handleChunk(e,t,n){const i=decodeURIComponent(escape(atob(e)));return n?t+i:i}async _getFolder(e){const t=new Map,n=await this.storage;await n.iterate(((e,n)=>{n.includes("/")||t.set(e.path,e)}));for(const n of(await this._getServerDirectory(e)).values())t.has(n.path)||t.set(n.path,n);return e&&0===t.size?null:{name:"",path:e,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:"json",mimetype:s.vJ.JSON,content:Array.from(t.values()),size:0,writable:!0,type:"directory"}}async _getServerContents(e,t){const n=i.PathExt.basename(e);let r=(await this._getServerDirectory(i.URLExt.join(e,".."))).get(n);if(!r)return null;if(r=r||{name:n,path:e,last_modified:new Date(0).toISOString(),created:new Date(0).toISOString(),format:"text",mimetype:s.vJ.PLAIN_TEXT,type:"file",writable:!0,size:0,content:""},null==t?void 0:t.content)if("directory"===r.type){const t=await this._getServerDirectory(e);r={...r,content:Array.from(t.values())}}else{const t=i.URLExt.join(i.PageConfig.getBaseUrl(),"files",e),o=await fetch(t);if(!o.ok)return null;const a=r.mimetype||o.headers.get("Content-Type"),l=i.PathExt.extname(n);if("notebook"===r.type||s.HB.hasFormat(l,"json")||-1!==(null==a?void 0:a.indexOf("json"))||e.match(/\.(ipynb|[^/]*json[^/]*)$/)){const e=await o.text();r={...r,content:JSON.parse(e),format:"json",mimetype:r.mimetype||s.vJ.JSON,size:e.length}}else if(s.HB.hasFormat(l,"text")||-1!==a.indexOf("text")){const e=await o.text();r={...r,content:e,format:"text",mimetype:a||s.vJ.PLAIN_TEXT,size:e.length}}else{const e=await o.arrayBuffer(),t=new Uint8Array(e);r={...r,content:btoa(t.reduce(this.reduceBytesToString,"")),format:"base64",mimetype:a||s.vJ.OCTET_STREAM,size:t.length}}}return r}async _getServerDirectory(e){const t=this._serverContents.get(e)||new Map;if(!this._serverContents.has(e)){const n=i.URLExt.join(i.PageConfig.getBaseUrl(),"api/contents",e,"all.json");try{const e=await fetch(n),i=JSON.parse(await e.text());for(const e of i.content)t.set(e.name,e)}catch(e){console.warn(`don't worry, about ${e}... nothing's broken. If there had been a\n file at ${n}, you might see some more files.`)}this._serverContents.set(e,t)}return t}async _incrementCounter(e){var t;const n=await this.counters,i=(null!==(t=await n.getItem(e))&&void 0!==t?t:-1)+1;return await n.setItem(e,i),i}}var l;!function(e){e.EMPTY_NB={metadata:{orig_nbformat:4},nbformat_minor:4,nbformat:4,cells:[]}}(l||(l={}));const c=16895;new TextEncoder,new TextDecoder("utf-8");class u{constructor(e){this.isDisposed=!1,this._onMessage=async e=>{if(!this._channel)return;const{_contents:t}=this,n=e.data,s=null==n?void 0:n.path;if("broadcast.ts"!==(null==n?void 0:n.receiver))return;let r,o=null;switch(null==n?void 0:n.method){case"readdir":r=await t.get(s,{content:!0}),o=[],"directory"===r.type&&r.content&&(o=r.content.map((e=>e.name)));break;case"rmdir":await t.delete(s);break;case"rename":await t.rename(s,n.data.newPath);break;case"getmode":r=await t.get(s),o="directory"===r.type?c:33206;break;case"lookup":try{r=await t.get(s),o={ok:!0,mode:"directory"===r.type?c:33206}}catch(e){o={ok:!1}}break;case"mknod":r=await t.newUntitled({path:i.PathExt.dirname(s),type:Number.parseInt(n.data.mode)===c?"directory":"file",ext:i.PathExt.extname(s)}),await t.rename(r.path,s);break;case"getattr":{r=await t.get(s);const e=new Date(0).toISOString();o={dev:1,nlink:1,uid:0,gid:0,rdev:0,size:r.size||0,blksize:4096,blocks:Math.ceil(r.size||0),atime:r.last_modified||e,mtime:r.last_modified||e,ctime:r.created||e,timestamp:0};break}case"get":if(r=await t.get(s,{content:!0}),"directory"===r.type)break;o={content:"json"===r.format?JSON.stringify(r.content):r.content,format:r.format};break;case"put":await t.save(s,{content:"json"===n.data.format?JSON.parse(n.data.data):n.data.data,type:"file",format:n.data.format});break;default:o=null}this._channel.postMessage(o)},this._channel=null,this._enabled=!1,this._contents=e.contents}get enabled(){return this._enabled}enable(){this._channel?console.warn("BroadcastChannel already created and enabled"):(this._channel=new BroadcastChannel("/api/drive.v1"),this._channel.addEventListener("message",this._onMessage),this._enabled=!0)}disable(){this._channel&&(this._channel.removeEventListener("message",this._onMessage),this._channel=null),this._enabled=!1}dispose(){this.isDisposed||(this.disable(),this.isDisposed=!0)}}var d,h=n(9842),p=n(4016);class f{constructor(e={}){if(this._map=new Map,this._changed=new p.Signal(this),this._isDisposed=!1,this._itemCmp=e.itemCmp||d.itemCmp,e.values)for(const t in e.values)this._map.set(t,e.values[t])}get type(){return"Map"}get changed(){return this._changed}get isDisposed(){return this._isDisposed}get size(){return this._map.size}set(e,t){const n=this._map.get(e);if(void 0===t)throw Error("Cannot set an undefined value, use remove");const i=this._itemCmp;return void 0!==n&&i(n,t)||(this._map.set(e,t),this._changed.emit({type:n?"change":"add",key:e,oldValue:n,newValue:t})),n}get(e){return this._map.get(e)}has(e){return this._map.has(e)}keys(){const e=[];return this._map.forEach(((t,n)=>{e.push(n)})),e}values(){const e=[];return this._map.forEach(((t,n)=>{e.push(t)})),e}delete(e){const t=this._map.get(e);return this._map.delete(e)&&this._changed.emit({type:"remove",key:e,oldValue:t,newValue:void 0}),t}clear(){const e=this.keys();for(let t=0;tthis._queue.push({resolve:e,reject:t})));return e||this._dispatch(),t}runExclusive(e){return y(this,void 0,void 0,(function*(){const[t,n]=yield this.acquire();try{return yield e(t)}finally{n()}}))}waitForUnlock(){return y(this,void 0,void 0,(function*(){return this.isLocked()?new Promise((e=>this._waiters.push({resolve:e}))):Promise.resolve()}))}isLocked(){return this._value<=0}release(){if(this._maxConcurrency>1)throw new Error("this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead");if(this._currentReleaser){const e=this._currentReleaser;this._currentReleaser=void 0,e()}}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatch(){const e=this._queue.shift();if(!e)return;let t=!1;this._currentReleaser=()=>{t||(t=!0,this._value++,this._resolveWaiters(),this._dispatch())},e.resolve([this._value--,this._currentReleaser])}_resolveWaiters(){this._waiters.forEach((e=>e.resolve())),this._waiters=[]}}class w{constructor(e){this._semaphore=new b(1,e)}acquire(){return e=this,t=void 0,i=function*(){const[,e]=yield this._semaphore.acquire();return e},new((n=void 0)||(n=Promise))((function(s,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function a(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}l((i=i.apply(e,t||[])).next())}));var e,t,n,i}runExclusive(e){return this._semaphore.runExclusive((()=>e()))}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const D=g.supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg;class x{constructor(e){this._kernels=new f,this._clients=new f,this._kernelClients=new f;const{kernelspecs:t}=e;this._kernelspecs=t}async startNew(e){const{id:t,name:n,location:i}=e,s=this._kernelspecs.factories.get(n);if(!s)return{id:t,name:n};const o=new w,a=(e,t,n)=>{var i;const s=this._kernels.get(e);if(!s)throw Error(`No kernel ${e}`);this._clients.set(t,n),null===(i=this._kernelClients.get(e))||void 0===i||i.add(t),n.on("message",(async e=>{let t;if(e instanceof ArrayBuffer)e=new Uint8Array(e).buffer,t=(0,m.deserialize)(e,D);else{if("string"!=typeof e)return;{const n=(new TextEncoder).encode(e);t=(0,m.deserialize)(n.buffer,D)}}"input_reply"===t.header.msg_type?s.handleMessage(t):(async e=>{await o.runExclusive((async()=>{await s.ready,await s.handleMessage(e)}))})(t)}));const r=()=>{var n;this._clients.delete(t),null===(n=this._kernelClients.get(e))||void 0===n||n.delete(t)};s.disposed.connect(r),n.onclose=r},l=null!=t?t:r.UUID.uuid4(),c=`${x.WS_BASE_URL}api/kernels/${l}/channels`,u=this._kernels.get(l);if(u)return{id:u.id,name:u.name};const d=await s({id:l,sendMessage:e=>{const t=e.header.session,n=this._clients.get(t);if(!n)return void console.warn(`Trying to send message on removed socket for kernel ${l}`);const i=(0,m.serialize)(e,D);if("iopub"!==e.channel)n.send(i);else{const e=this._kernelClients.get(l);null==e||e.forEach((e=>{var t;null===(t=this._clients.get(e))||void 0===t||t.send(i)}))}},name:n,location:i});this._kernels.set(l,d),this._kernelClients.set(l,new Set);const h=new v.Server(c,{mock:!1,selectProtocol:()=>D});return h.on("connection",(e=>{var t;const n=null!==(t=new URL(e.url).searchParams.get("session_id"))&&void 0!==t?t:"";a(l,n,e)})),h.on("close",(()=>{this._clients.keys().forEach((e=>{var t;const n=this._clients.get(e);(null==n?void 0:n.readyState)===WebSocket.CLOSED&&(this._clients.delete(e),null===(t=this._kernelClients.get(l))||void 0===t||t.delete(e))}))})),d.disposed.connect((()=>{h.close(),this._kernels.delete(l),this._kernelClients.delete(l)})),{id:d.id,name:d.name}}async restart(e){const t=this._kernels.get(e);if(!t)throw Error(`Kernel ${e} does not exist`);const{id:n,name:i,location:s}=t;return t.dispose(),this.startNew({id:n,name:i,location:s})}async list(){return[...this._kernels.values()].map((e=>({id:e.id,name:e.name})))}async shutdown(e){var t;null===(t=this._kernels.delete(e))||void 0===t||t.dispose()}async get(e){return this._kernels.get(e)}}!function(e){e.WS_BASE_URL=i.PageConfig.getBaseUrl().replace(/^http/,"ws")}(x||(x={}));class C{constructor(){this._specs=new Map,this._factories=new Map}get specs(){return 0===this._specs.size?null:{default:this.defaultKernelName,kernelspecs:Object.fromEntries(this._specs)}}get defaultKernelName(){let e=i.PageConfig.getOption("defaultKernelName");if(!e&&this._specs.size){const t=Array.from(this._specs.keys());t.sort(),e=t[0]}return e||h.vM}get factories(){return this._factories}register(e){const{spec:t,create:n}=e;this._specs.set(t.name,t),this._factories.set(t.name,n)}}const E="third-party-licenses.json",S=new r.Token("@jupyterlite/licenses:ILicenses"),A=Object.freeze({packages:[]});class k{async get(){return{bundles:{...await this._getFederated(),[this.appName]:await this._getAppLicenses()}}}get appName(){return i.PageConfig.getOption("appName")||"JupyterLite"}get appLicensesUrl(){return i.URLExt.join(i.PageConfig.getBaseUrl(),"build",E)}get labExtensionsUrl(){return i.PageConfig.getOption("fullLabextensionsUrl")}async _getAppLicenses(){let e=A;try{e=(await fetch(this.appLicensesUrl)).json()}catch(e){console.warn("Could not resolve licenses for",this.appName)}return e}async _getFederated(){const e={};let t;try{t=JSON.parse(i.PageConfig.getOption("federated_extensions"))}catch{return e}const n=[];for(const i of t)n.push(this._getOneFederated(i,e));try{await Promise.all(n)}catch(e){console.warn("Error resolving licenses",e)}return e}async _getOneFederated(e,t){try{const n=i.URLExt.join(this.labExtensionsUrl,e.name,"static",E),s=await fetch(n);t[e.name]=await s.json()}catch{console.warn("Could not resolve licenses for",e),t[e.name]=A}}}var M=n(4374),F=n(3570);const I=new r.Token("@jupyterlite/session:ISessions");var O=n(5259);class P{constructor(e){this._sessions=[],this._kernels=e.kernels}async get(e){const t=this._sessions.find((t=>t.id===e));if(!t)throw Error(`Session ${e} not found`);return t}async list(){return this._sessions}async patch(e){const{id:t,path:n,name:s,kernel:o}=e,a=this._sessions.findIndex((e=>e.id===t)),l=this._sessions[a];if(!l)throw Error(`Session ${t} not found`);const c={...l,path:null!=n?n:l.path,name:null!=s?s:l.name};if(o)if(o.id){const e=this._sessions.find((e=>{var t;return(null===(t=e.kernel)||void 0===t?void 0:t.id)===(null==o?void 0:o.id)}));e&&(c.kernel=e.kernel)}else if(o.name){const e=await this._kernels.startNew({id:r.UUID.uuid4(),name:o.name,location:i.PathExt.dirname(c.path)});e&&(c.kernel=e),this._handleKernelShutdown({kernelId:e.id,sessionId:l.id})}return this._sessions[a]=c,c}async startNew(e){var t,n,s,o;const{path:a,name:l}=e,c=this._sessions.find((e=>e.name===l));if(c)return c;const u=null!==(n=null===(t=e.kernel)||void 0===t?void 0:t.name)&&void 0!==n?n:"",d=null!==(s=e.id)&&void 0!==s?s:r.UUID.uuid4(),h=null!==(o=e.name)&&void 0!==o?o:e.path,p=i.PathExt.dirname(e.name)||i.PathExt.dirname(e.path),f=h.includes(":")?h.split(":")[0]:"",m=p.includes(f)?p:`${f}:${p}`,g=await this._kernels.startNew({id:d,name:u,location:m}),v={id:d,path:a,name:null!=l?l:a,type:"notebook",kernel:{id:g.id,name:g.name}};return this._sessions.push(v),this._handleKernelShutdown({kernelId:d,sessionId:v.id}),v}async shutdown(e){var t;const n=this._sessions.find((t=>t.id===e));if(!n)throw Error(`Session ${e} not found`);const i=null===(t=n.kernel)||void 0===t?void 0:t.id;i&&await this._kernels.shutdown(i),O.RO.removeFirstOf(this._sessions,n)}async _handleKernelShutdown({kernelId:e,sessionId:t}){const n=await this._kernels.get(e);n&&n.disposed.connect((()=>{this.shutdown(t)}))}}const B=new r.Token("@jupyterlite/settings:ISettings");var R=n(6111);const T="JupyterLite Storage";class L{constructor(e){this._storageName=T,this._storageDrivers=null,this._localforage=e.localforage,this._storageName=e.storageName||T,this._storageDrivers=e.storageDrivers||null,this._ready=new r.PromiseDelegate}get ready(){return this._ready.promise}get storage(){return this.ready.then((()=>this._storage))}async initialize(){await this.initStorage(),this._ready.resolve(void 0)}async initStorage(){this._storage=this.defaultSettingsStorage()}get defaultStorageOptions(){var e;const t=(null===(e=this._storageDrivers)||void 0===e?void 0:e.length)?this._storageDrivers:null;return{version:1,name:this._storageName,...t?{driver:t}:{}}}defaultSettingsStorage(){return this._localforage.createInstance({description:"Offline Storage for Settings",storeName:"settings",...this.defaultStorageOptions})}async get(e){return(await this.getAll()).settings.find((t=>t.id===e))}async getAll(){const[e,t]=await Promise.all([this._getAll("all.json"),this._getAll("all_federated.json")]),n=e.concat(t),i=await this.storage;return{settings:await Promise.all(n.map((async e=>{var t;const{id:n}=e,s=null!==(t=await i.getItem(n))&&void 0!==t?t:e.raw;return{...j.override(e),raw:s,settings:R.parse(s)}})))}}async save(e,t){await(await this.storage).setItem(e,t)}async _getAll(e){var t;const n=null!==(t=i.PageConfig.getOption("settingsUrl"))&&void 0!==t?t:"/";return await(await fetch(i.URLExt.join(n,e))).json()}}var j;!function(e){const t=JSON.parse(i.PageConfig.getOption("settingsOverrides")||"{}");e.override=function(e){if(t[e.id]){e.schema.properties||(e.schema.properties={});for(const[n,i]of Object.entries(t[e.id]||{}))e.schema.properties[n].default=i}return e}}(j||(j={}));const N=new r.Token("@jupyterlite/translation:ITranslation");class z{constructor(){this._prevLocale=""}async get(e){const t=i.URLExt.join(i.PageConfig.getBaseUrl(),`api/translations/${e}.json`);try{const n=await fetch(t),i=JSON.parse(await n.text());if("all"!==this._prevLocale&&"all"===e){const e=this._prevLocale;i.data[e].displayName=i.data[e].nativeName,"en"!==e&&(i.data.en.displayName=`${i.data.en.nativeName} (default)`)}return this._prevLocale=e,i}catch(t){return e?{data:{},message:`Language pack '${e}' not installed!`}:{data:{en:{displayName:"English",nativeName:"English"}},message:""}}}}const U=new r.Token("@jupyterlite/localforge:ILocalForage");var q=n(1976),W=n.n(q),H=n(5486),K=n.n(H);const $={id:"@jupyterlite/server-extension:localforage",autoStart:!0,provides:U,activate:e=>({localforage:K()})},V={id:"@jupyterlite/server-extension:localforage-memory-storage",autoStart:!0,requires:[U],activate:async(e,t)=>{JSON.parse(i.PageConfig.getOption("enableMemoryStorage")||"false")&&(console.warn("Memory storage fallback enabled: contents and settings may not be saved"),await async function(e){return await e.defineDriver(W())}(t.localforage))}},J={id:"@jupyterlite/server-extension:contents",requires:[U],autoStart:!0,provides:s.Hv,activate:(e,t)=>{const n=i.PageConfig.getOption("contentsStorageName"),s=JSON.parse(i.PageConfig.getOption("contentsStorageDrivers")||"null"),{localforage:r}=t,o=new a({storageName:n,storageDrivers:s,localforage:r});return e.started.then((()=>o.initialize().catch(console.warn))),o}},G={id:"@jupyterlite/server-extension:contents-routes",autoStart:!0,requires:[s.Hv],activate:(e,t)=>{e.router.get("/api/contents/(.+)/checkpoints",(async(e,n)=>{const i=await t.listCheckpoints(n);return new Response(JSON.stringify(i))})),e.router.post("/api/contents/(.+)/checkpoints/(.*)",(async(e,n,i)=>{const s=await t.restoreCheckpoint(n,i);return new Response(JSON.stringify(s),{status:204})})),e.router.post("/api/contents/(.+)/checkpoints",(async(e,n)=>{const i=await t.createCheckpoint(n);return new Response(JSON.stringify(i),{status:201})})),e.router.delete("/api/contents/(.+)/checkpoints/(.*)",(async(e,n,i)=>{const s=await t.deleteCheckpoint(n,i);return new Response(JSON.stringify(s),{status:204})})),e.router.get("/api/contents(.*)",(async(e,n)=>{var i;const s={content:"1"===(null===(i=e.query)||void 0===i?void 0:i.content)},r=await t.get(n,s);return r?new Response(JSON.stringify(r)):new Response(null,{status:404})})),e.router.post("/api/contents(.*)",(async(e,n)=>{const i=e.body,s=null==i?void 0:i.copy_from;let r;return r=s?await t.copy(s,n):await t.newUntitled(i),r?new Response(JSON.stringify(r),{status:201}):new Response(null,{status:400})})),e.router.patch("/api/contents(.*)",(async(e,n)=>{var i,s;const r=null!==(s=null===(i=e.body)||void 0===i?void 0:i.path)&&void 0!==s?s:"";n="/"===n[0]?n.slice(1):n;const o=await t.rename(n,r);return new Response(JSON.stringify(o))})),e.router.put("/api/contents/(.+)",(async(e,n)=>{const i=e.body,s=await t.save(n,i);return new Response(JSON.stringify(s))})),e.router.delete("/api/contents/(.+)",(async(e,n)=>(await t.delete(n),new Response(null,{status:204}))))}},Y={id:"@jupyterlite/server-extension:service-worker",autoStart:!0,provides:M.f,activate:e=>new F.Z},X={id:"@jupyterlite/server-extension:settings",autoStart:!0,requires:[U],provides:B,activate:(e,t)=>{const n=i.PageConfig.getOption("settingsStorageName"),s=JSON.parse(i.PageConfig.getOption("settingsStorageDrivers")||"null"),{localforage:r}=t,o=new L({storageName:n,storageDrivers:s,localforage:r});return e.started.then((()=>o.initialize().catch(console.warn))),o}},Z={id:"@jupyterlite/server-extension:settings-routes",autoStart:!0,requires:[B],activate:(e,t)=>{const n="/api/settings/((?:@([^/]+?)[/])?([^/]+?):([^:]+))$";e.router.get(n,(async(e,n)=>{const i=await t.get(n);return new Response(JSON.stringify(i))})),e.router.put(n,(async(e,n)=>{const i=e.body,{raw:s}=i;return await t.save(n,s),new Response(null,{status:204})})),e.router.get("/api/settings",(async e=>{const n=await t.getAll();return new Response(JSON.stringify(n))}))}},Q=[J,G,{id:"@jupyterlite/server-extension:emscripten-filesystem",autoStart:!0,optional:[M.f],provides:s.dC,activate:(e,t)=>{const{contents:n}=e.serviceManager,i=new u({contents:n}),s="Kernel filesystem and JupyterLite contents";function r(e,t){t&&console.warn(t),e&&console.warn(e),t||e?console.warn(`${s} will NOT be synced`):console.info(`${s} will be synced`)}return t?t.ready.then((()=>{i.enable(),r()})).catch((e=>{r("JupyterLite ServiceWorker failed to become available",e)})):r("JupyterLite ServiceWorker not available"),i}},{id:"@jupyterlite/server-extension:kernels",autoStart:!0,provides:h.Ll,requires:[h.qP],activate:(e,t)=>new x({kernelspecs:t})},{id:"@jupyterlite/server-extension:kernels-routes",autoStart:!0,requires:[h.Ll],activate:(e,t)=>{e.router.get("/api/kernels",(async e=>{const n=await t.list();return new Response(JSON.stringify(n))})),e.router.post("/api/kernels/(.*)/restart",(async(e,n)=>{const i=await t.restart(n);return new Response(JSON.stringify(i))})),e.router.delete("/api/kernels/(.*)",(async(e,n)=>{const i=await t.shutdown(n);return new Response(JSON.stringify(i),{status:204})}))}},{id:"@jupyterlite/server-extension:kernelspec",autoStart:!0,provides:h.qP,activate:e=>new C},{id:"@jupyterlite/server-extension:kernelspec-routes",autoStart:!0,requires:[h.qP],activate:(e,t)=>{e.router.get("/api/kernelspecs",(async e=>{const{specs:n}=t;if(!n)return new Response(null);const i={},s=n.kernelspecs;Object.keys(s).forEach((e=>{const t=s[e],{resources:n}=null!=t?t:{};i[e]={name:e,spec:t,resources:n}}));const r={default:n.default,kernelspecs:i};return new Response(JSON.stringify(r))}))}},{id:"@jupyterlite/server-extension:licenses",autoStart:!0,provides:S,activate:e=>new k},{id:"@jupyterlite/server-extension:licenses-routes",autoStart:!0,requires:[S],activate(e,t){e.router.get("/api/licenses",(async e=>{const n=await t.get();return new Response(JSON.stringify(n))}))}},V,$,{id:"@jupyterlite/server-extension:lsp-routes",autoStart:!0,activate:e=>{e.router.get("/lsp/status",(async e=>new Response(JSON.stringify({version:2,sessions:{},specs:{}}))))}},{id:"@jupyterlite/server-extension:nbconvert-routes",autoStart:!0,activate:e=>{e.router.get("/api/nbconvert",(async e=>new Response(JSON.stringify({}))))}},Y,{id:"@jupyterlite/server-extension:sessions",autoStart:!0,provides:I,requires:[h.Ll],activate:(e,t)=>new P({kernels:t})},{id:"@jupyterlite/server-extension:sessions-routes",autoStart:!0,requires:[I],activate:(e,t)=>{e.router.get("/api/sessions/(.+)",(async(e,n)=>{const i=await t.get(n);return new Response(JSON.stringify(i),{status:200})})),e.router.get("/api/sessions",(async e=>{const n=await t.list();return new Response(JSON.stringify(n),{status:200})})),e.router.patch("/api/sessions(.*)",(async(e,n)=>{const i=e.body,s=await t.patch(i);return new Response(JSON.stringify(s),{status:200})})),e.router.delete("/api/sessions/(.+)",(async(e,n)=>(await t.shutdown(n),new Response(null,{status:204})))),e.router.post("/api/sessions",(async e=>{const n=e.body,i=await t.startNew(n);return new Response(JSON.stringify(i),{status:201})}))}},X,Z,{id:"@jupyterlite/server-extension:translation",autoStart:!0,provides:N,activate:e=>{const t=new z;return e.router.get("/api/translations/?(.*)",(async(e,n)=>{"default"===n&&(n="en");const i=await t.get(n||"all");return new Response(JSON.stringify(i))})),t}},{id:"@jupyterlite/server-extension:translation-routes",autoStart:!0,requires:[N],activate:(e,t)=>{e.router.get("/api/translations/?(.*)",(async(e,n)=>{const i=await t.get(n||"all");return new Response(JSON.stringify(i))}))}}]},3800:(e,t,n)=>{"use strict";n.r(t),n.d(t,{IServiceWorkerManager:()=>ct.f,JupyterLiteServer:()=>lt,Router:()=>ot,ServiceWorkerManager:()=>ut.Z,WORKER_NAME:()=>ct.o});var i,s,r,o,a,l,c,u=n(6914),d=n(5259),h=n(5082),p=n(4016);class f{constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class m{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(m||(m={}));class g extends m{constructor(){super(...arguments),this._disposed=new p.Signal(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),p.Signal.clearData(this))}}function v(){return b.keyboardLayout}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(g||(g={})),function(e){e.copyText=function(e){const t=document.body,n=i=>{i.preventDefault(),i.stopPropagation(),i.clipboardData.setData("text",e),t.removeEventListener("copy",n,!0)};t.addEventListener("copy",n,!0),document.execCommand("copy")}}(i||(i={})),(c=s||(s={})).boxSizing=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,i=parseFloat(t.borderLeftWidth)||0,s=parseFloat(t.borderRightWidth)||0,r=parseFloat(t.borderBottomWidth)||0,o=parseFloat(t.paddingTop)||0,a=parseFloat(t.paddingLeft)||0,l=parseFloat(t.paddingRight)||0,c=parseFloat(t.paddingBottom)||0;return{borderTop:n,borderLeft:i,borderRight:s,borderBottom:r,paddingTop:o,paddingLeft:a,paddingRight:l,paddingBottom:c,horizontalSum:i+a+l+s,verticalSum:n+o+c+r}},c.sizeLimits=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.minWidth)||0,i=parseFloat(t.minHeight)||0,s=parseFloat(t.maxWidth)||1/0,r=parseFloat(t.maxHeight)||1/0;return s=Math.max(n,s),r=Math.max(i,r),{minWidth:n,minHeight:i,maxWidth:s,maxHeight:r}},c.hitTest=function(e,t,n){let i=e.getBoundingClientRect();return t>=i.left&&t=i.top&&n=n.bottom||(i.topn.bottom&&i.height>=n.height?e.scrollTop-=n.top-i.top:(i.topn.height||i.bottom>n.bottom&&i.height{let e=Element.prototype;return e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(e){let t=this,n=t.ownerDocument?t.ownerDocument.querySelectorAll(e):[];return-1!==Array.prototype.indexOf.call(n,t)}})(),e.calculateSingle=function(e){let c=0,u=0,d=0;function h(t){let n=e.match(t);return null!==n&&(e=e.slice(n[0].length),!0)}for(e=(e=e.split(",",1)[0]).replace(l," $1 ");e.length>0;)if(h(t))c++;else if(h(n))u++;else if(h(i))u++;else if(h(r))d++;else if(h(o))u++;else if(h(s))d++;else if(!h(a))return 0;return c=Math.min(c,255),u=Math.min(u,255),d=Math.min(d,255),c<<16|u<<8|d};const t=/^#[^\s\+>~#\.\[:]+/,n=/^\.[^\s\+>~#\.\[:]+/,i=/^\[[^\]]+\]/,s=/^[^\s\+>~#\.\[:]+/,r=/^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/,o=/^:[^\s\+>~#\.\[:]+/,a=/^[\s\+>~\*]+/,l=/:not\(([^\)]+)\)/g}(a||(a={}));class _{constructor(e,t,n=[]){this.name=e,this._codes=t,this._keys=_.extractKeys(t),this._modifierKeys=_.convertToKeySet(n)}keys(){return Object.keys(this._keys)}isValidKey(e){return e in this._keys}isModifierKey(e){return e in this._modifierKeys}keyForKeydownEvent(e){return this._codes[e.keyCode]||""}}!function(e){e.extractKeys=function(e){let t=Object.create(null);for(let n in e)t[e[n]]=!0;return t},e.convertToKeySet=function(e){let t=Object(null);for(let n=0,i=e.length;n{this._commands.delete(e),this._commandChanged.emit({id:e,type:"removed"})}))}notifyCommandChanged(e){if(void 0!==e&&!this._commands.has(e))throw new Error(`Command '${e}' is not registered.`);this._commandChanged.emit({id:e,type:e?"changed":"many-changed"})}describedBy(e,t=h.JSONExt.emptyObject){var n;let i=this._commands.get(e);return Promise.resolve(null!==(n=null==i?void 0:i.describedBy.call(void 0,t))&&void 0!==n?n:{args:null})}label(e,t=h.JSONExt.emptyObject){var n;let i=this._commands.get(e);return null!==(n=null==i?void 0:i.label.call(void 0,t))&&void 0!==n?n:""}mnemonic(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.mnemonic.call(void 0,t):-1}icon(e,t=h.JSONExt.emptyObject){var n;return null===(n=this._commands.get(e))||void 0===n?void 0:n.icon.call(void 0,t)}iconClass(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconClass.call(void 0,t):""}iconLabel(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconLabel.call(void 0,t):""}caption(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.caption.call(void 0,t):""}usage(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.usage.call(void 0,t):""}className(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.className.call(void 0,t):""}dataset(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.dataset.call(void 0,t):{}}isEnabled(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isEnabled.call(void 0,t)}isToggled(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggled.call(void 0,t)}isToggleable(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggleable}isVisible(e,t=h.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isVisible.call(void 0,t)}execute(e,t=h.JSONExt.emptyObject){let n,i=this._commands.get(e);if(!i)return Promise.reject(new Error(`Command '${e}' not registered.`));try{n=i.execute.call(void 0,t)}catch(e){n=Promise.reject(e)}let s=Promise.resolve(n);return this._commandExecuted.emit({id:e,args:t,result:s}),s}addKeyBinding(e){let t=w.createKeyBinding(e);return this._keyBindings.push(t),this._keyBindingChanged.emit({binding:t,type:"added"}),new f((()=>{d.RO.removeFirstOf(this._keyBindings,t),this._keyBindingChanged.emit({binding:t,type:"removed"})}))}processKeydownEvent(e){if(this._replaying||E.isModifierKeyPressed(e))return;let t=E.keystrokeForKeydownEvent(e);if(!t)return this._replayKeydownEvents(),void this._clearPendingState();this._keystrokes.push(t);let{exact:n,partial:i}=w.matchKeyBinding(this._keyBindings,this._keystrokes,e);return n||i?(e.preventDefault(),e.stopPropagation(),n&&!i?(this._executeKeyBinding(n),void this._clearPendingState()):(n&&(this._exactKeyMatch=n),this._keydownEvents.push(e),void this._startTimer())):(this._replayKeydownEvents(),void this._clearPendingState())}_startTimer(){this._clearTimer(),this._timerID=window.setTimeout((()=>{this._onPendingTimeout()}),w.CHORD_TIMEOUT)}_clearTimer(){0!==this._timerID&&(clearTimeout(this._timerID),this._timerID=0)}_replayKeydownEvents(){0!==this._keydownEvents.length&&(this._replaying=!0,this._keydownEvents.forEach(w.replayKeyEvent),this._replaying=!1)}_executeKeyBinding(e){let{command:t,args:n}=e,i={_luminoEvent:{type:"keybinding",keys:e.keys},...n};if(this.hasCommand(t)&&this.isEnabled(t,i))this.execute(t,i);else{let n=this.hasCommand(t)?"enabled":"registered",i=`Cannot execute key binding '${e.keys.join(", ")}':`,s=`command '${t}' is not ${n}.`;console.warn(`${i} ${s}`)}}_clearPendingState(){this._clearTimer(),this._exactKeyMatch=null,this._keystrokes.length=0,this._keydownEvents.length=0}_onPendingTimeout(){this._timerID=0,this._exactKeyMatch?this._executeKeyBinding(this._exactKeyMatch):this._replayKeydownEvents(),this._clearPendingState()}}function*S(){}function A(e,t){let n=0;for(const i of e)if(t(i,n++))return i}!function(e){function t(e){let t="",n=!1,i=!1,s=!1,o=!1;for(let a of e.split(/\s+/))"Accel"===a?r.IS_MAC?i=!0:s=!0:"Alt"===a?n=!0:"Cmd"===a?i=!0:"Ctrl"===a?s=!0:"Shift"===a?o=!0:a.length>0&&(t=a);return{cmd:i,ctrl:s,alt:n,shift:o,key:t}}function n(e){let n="",i=t(e);return i.ctrl&&(n+="Ctrl "),i.alt&&(n+="Alt "),i.shift&&(n+="Shift "),i.cmd&&r.IS_MAC&&(n+="Cmd "),n+i.key}e.parseKeystroke=t,e.normalizeKeystroke=n,e.normalizeKeys=function(e){let t;return t=r.IS_WIN?e.winKeys||e.keys:r.IS_MAC?e.macKeys||e.keys:e.linuxKeys||e.keys,t.map(n)},e.formatKeystroke=function(e){return"string"==typeof e?n(e):e.map(n).join(", ");function n(e){let n=[],i=r.IS_MAC?" ":"+",s=t(e);return s.ctrl&&n.push("Ctrl"),s.alt&&n.push("Alt"),s.shift&&n.push("Shift"),r.IS_MAC&&s.cmd&&n.push("Cmd"),n.push(s.key),n.map(w.formatKey).join(i)}},e.isModifierKeyPressed=function(e){let t=v(),n=t.keyForKeydownEvent(e);return t.isModifierKey(n)},e.keystrokeForKeydownEvent=function(e){let t=v(),n=t.keyForKeydownEvent(e);if(!n||t.isModifierKey(n))return"";let i=[];return e.ctrlKey&&i.push("Ctrl"),e.altKey&&i.push("Alt"),e.shiftKey&&i.push("Shift"),e.metaKey&&r.IS_MAC&&i.push("Cmd"),i.push(n),i.join(" ")}}(E||(E={})),function(e){e.CHORD_TIMEOUT=1e3,e.createCommand=function(e){return{execute:e.execute,describedBy:d("function"==typeof e.describedBy?e.describedBy:{args:null,...e.describedBy},(()=>({args:null}))),label:d(e.label,i),mnemonic:d(e.mnemonic,s),icon:d(e.icon,u),iconClass:d(e.iconClass,i),iconLabel:d(e.iconLabel,i),caption:d(e.caption,i),usage:d(e.usage,i),className:d(e.className,i),dataset:d(e.dataset,c),isEnabled:e.isEnabled||a,isToggled:e.isToggled||l,isToggleable:e.isToggleable||!!e.isToggled,isVisible:e.isVisible||a}},e.createKeyBinding=function(e){return{keys:E.normalizeKeys(e),selector:p(e),command:e.command,args:e.args||h.JSONExt.emptyObject}},e.matchKeyBinding=function(e,t,n){let i=null,s=!1,r=1/0,a=0;for(let l=0,c=e.length;lr)continue;let h=o.calculateSpecificity(c.selector);(!i||d=a)&&(i=c,r=d,a=h)}return{exact:i,partial:s}},e.replayKeyEvent=function(e){e.target.dispatchEvent(function(e){let t=document.createEvent("Event"),n=e.bubbles||!0,i=e.cancelable||!0;return t.initEvent(e.type||"keydown",n,i),t.key=e.key||"",t.keyCode=e.keyCode||0,t.which=e.keyCode||0,t.ctrlKey=e.ctrlKey||!1,t.altKey=e.altKey||!1,t.shiftKey=e.shiftKey||!1,t.metaKey=e.metaKey||!1,t.view=e.view||window,t}(e))},e.formatKey=function(e){return r.IS_MAC?t.hasOwnProperty(e)?t[e]:e:n.hasOwnProperty(e)?n[e]:e};const t={Backspace:"⌫",Tab:"⇥",Enter:"⏎",Shift:"⇧",Ctrl:"⌃",Alt:"⌥",Escape:"⎋",PageUp:"⇞",PageDown:"⇟",End:"↘",Home:"↖",ArrowLeft:"←",ArrowUp:"↑",ArrowRight:"→",ArrowDown:"↓",Delete:"⌦",Cmd:"⌘"},n={Escape:"Esc",PageUp:"Page Up",PageDown:"Page Down",ArrowLeft:"Left",ArrowUp:"Up",ArrowRight:"Right",ArrowDown:"Down",Delete:"Del"},i=()=>"",s=()=>-1,a=()=>!0,l=()=>!1,c=()=>({}),u=()=>{};function d(e,t){return void 0===e?t:"function"==typeof e?e:()=>e}function p(e){if(-1!==e.selector.indexOf(","))throw new Error(`Selector cannot contain commas: ${e.selector}`);if(!o.isValid(e.selector))throw new Error(`Invalid selector: ${e.selector}`);return e.selector}function f(e,t){if(e.lengtht.length?2:1}function m(e,t){let n=t.target,i=t.currentTarget;for(let t=0;null!==n;n=n.parentElement,++t){if(n.hasAttribute("data-lm-suppress-shortcuts"))return-1;if(o.matches(n,e))return t;if(n===i)return-1}return-1}}(w||(w={})),function(e){function t(e,t,n=0,i=-1){let s,r=e.length;if(0===r)return-1;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(D||(D={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(C||(C={}));var k,M,F,I,O,P,B,R,T,L,j,N=n(8743);!function(e){e.copyText=function(e){const t=document.body,n=i=>{i.preventDefault(),i.stopPropagation(),i.clipboardData.setData("text",e),t.removeEventListener("copy",n,!0)};t.addEventListener("copy",n,!0),document.execCommand("copy")}}(k||(k={})),function(e){e.boxSizing=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.borderTopWidth)||0,i=parseFloat(t.borderLeftWidth)||0,s=parseFloat(t.borderRightWidth)||0,r=parseFloat(t.borderBottomWidth)||0,o=parseFloat(t.paddingTop)||0,a=parseFloat(t.paddingLeft)||0,l=parseFloat(t.paddingRight)||0,c=parseFloat(t.paddingBottom)||0;return{borderTop:n,borderLeft:i,borderRight:s,borderBottom:r,paddingTop:o,paddingLeft:a,paddingRight:l,paddingBottom:c,horizontalSum:i+a+l+s,verticalSum:n+o+c+r}},e.sizeLimits=function(e){let t=window.getComputedStyle(e),n=parseFloat(t.minWidth)||0,i=parseFloat(t.minHeight)||0,s=parseFloat(t.maxWidth)||1/0,r=parseFloat(t.maxHeight)||1/0;return s=Math.max(n,s),r=Math.max(i,r),{minWidth:n,minHeight:i,maxWidth:s,maxHeight:r}},e.hitTest=function(e,t,n){let i=e.getBoundingClientRect();return t>=i.left&&t=i.top&&n=n.bottom||(i.topn.bottom&&i.height>=n.height?e.scrollTop-=n.top-i.top:(i.topn.height||i.bottom>n.bottom&&i.height{let e=Element.prototype;return e.matches||e.matchesSelector||e.mozMatchesSelector||e.msMatchesSelector||e.oMatchesSelector||e.webkitMatchesSelector||function(e){let t=this,n=t.ownerDocument?t.ownerDocument.querySelectorAll(e):[];return-1!==Array.prototype.indexOf.call(n,t)}})(),e.calculateSingle=function(e){let c=0,u=0,d=0;function h(t){let n=e.match(t);return null!==n&&(e=e.slice(n[0].length),!0)}for(e=(e=e.split(",",1)[0]).replace(l," $1 ");e.length>0;)if(h(t))c++;else if(h(n))u++;else if(h(i))u++;else if(h(r))d++;else if(h(o))u++;else if(h(s))d++;else if(!h(a))return 0;return c=Math.min(c,255),u=Math.min(u,255),d=Math.min(d,255),c<<16|u<<8|d};const t=/^#[^\s\+>~#\.\[:]+/,n=/^\.[^\s\+>~#\.\[:]+/,i=/^\[[^\]]+\]/,s=/^[^\s\+>~#\.\[:]+/,r=/^(::[^\s\+>~#\.\[:]+|:first-line|:first-letter|:before|:after)/,o=/^:[^\s\+>~#\.\[:]+/,a=/^[\s\+>~\*]+/,l=/:not\(([^\)]+)\)/g}(O||(O={}));class z{constructor(){this._first=null,this._last=null,this._size=0}get isEmpty(){return 0===this._size}get size(){return this._size}get length(){return this._size}get first(){return this._first?this._first.value:void 0}get last(){return this._last?this._last.value:void 0}get firstNode(){return this._first}get lastNode(){return this._last}*[Symbol.iterator](){let e=this._first;for(;e;)yield e.value,e=e.next}*retro(){let e=this._last;for(;e;)yield e.value,e=e.prev}*nodes(){let e=this._first;for(;e;)yield e,e=e.next}*retroNodes(){let e=this._last;for(;e;)yield e,e=e.prev}assign(e){this.clear();for(const t of e)this.addLast(t)}push(e){this.addLast(e)}pop(){return this.removeLast()}shift(e){this.addFirst(e)}unshift(){return this.removeFirst()}addFirst(e){let t=new P.LinkedListNode(this,e);return this._first?(t.next=this._first,this._first.prev=t,this._first=t):(this._first=t,this._last=t),this._size++,t}addLast(e){let t=new P.LinkedListNode(this,e);return this._last?(t.prev=this._last,this._last.next=t,this._last=t):(this._first=t,this._last=t),this._size++,t}insertBefore(e,t){if(!t||t===this._first)return this.addFirst(e);if(!(t instanceof P.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");let n=new P.LinkedListNode(this,e),i=t,s=i.prev;return n.next=i,n.prev=s,i.prev=n,s.next=n,this._size++,n}insertAfter(e,t){if(!t||t===this._last)return this.addLast(e);if(!(t instanceof P.LinkedListNode)||t.list!==this)throw new Error("Reference node is not owned by the list.");let n=new P.LinkedListNode(this,e),i=t,s=i.next;return n.next=s,n.prev=i,i.next=n,s.prev=n,this._size++,n}removeFirst(){let e=this._first;if(e)return e===this._last?(this._first=null,this._last=null):(this._first=e.next,this._first.prev=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value}removeLast(){let e=this._last;if(e)return e===this._first?(this._first=null,this._last=null):(this._last=e.prev,this._last.next=null),e.list=null,e.next=null,e.prev=null,this._size--,e.value}removeNode(e){if(!(e instanceof P.LinkedListNode)||e.list!==this)throw new Error("Node is not owned by the list.");let t=e;t===this._first&&t===this._last?(this._first=null,this._last=null):t===this._first?(this._first=t.next,this._first.prev=null):t===this._last?(this._last=t.prev,this._last.next=null):(t.next.prev=t.prev,t.prev.next=t.next),t.list=null,t.next=null,t.prev=null,this._size--}clear(){let e=this._first;for(;e;){let t=e.next;e.list=null,e.prev=null,e.next=null,e=t}this._first=null,this._last=null,this._size=0}}!function(e){e.from=function(t){let n=new e;return n.assign(t),n}}(z||(z={})),function(e){e.LinkedListNode=class{constructor(e,t){this.list=null,this.next=null,this.prev=null,this.list=e,this.value=t}}}(P||(P={}));class U{constructor(e){this.type=e}get isConflatable(){return!1}conflate(e){return!1}}class q extends U{get isConflatable(){return!0}conflate(e){return!0}}!function(e){let t=null;const n=(i=Promise.resolve(),e=>{let t=!1;return i.then((()=>!t&&e())),()=>{t=!0}});var i;function s(e,t){let n=o.get(e);if(!n||0===n.length)return void u(e,t);let i=function(e,t){let n=0;for(const i of e)if(!1===t(i,n++))return!1;return!0}(function*(e){if("function"==typeof e.retro)yield*e.retro();else for(let t=e.length-1;t>-1;t--)yield e[t]}(n),(n=>!n||function(e,t,n){let i=!0;try{i="function"==typeof e?e(t,n):e.messageHook(t,n)}catch(e){l(e)}return i}(n,e,t)));i&&u(e,t)}e.sendMessage=s,e.postMessage=function(e,t){t.isConflatable&&function(n,i){for(const i of n)if((s=i).handler===e&&s.msg&&s.msg.type===t.type&&s.msg.isConflatable&&s.msg.conflate(t))return!0;var s;return!1}(r)||d(e,t)},e.installMessageHook=function(e,t){let n=o.get(e);n&&-1!==n.indexOf(t)||(n?n.push(t):o.set(e,[t]))},e.removeMessageHook=function(e,t){let n=o.get(e);if(!n)return;let i=n.indexOf(t);-1!==i&&(n[i]=null,p(n))},e.clearData=function(e){let t=o.get(e);t&&t.length>0&&(D.fill(t,null),p(t));for(const t of r)t.handler===e&&(t.handler=null,t.msg=null)},e.flush=function(){c||null===t||(t(),t=null,c=!0,h(),c=!1)},e.getExceptionHandler=function(){return l},e.setExceptionHandler=function(e){let t=l;return l=e,t};const r=new z,o=new WeakMap,a=new Set;let l=e=>{console.error(e)},c=!1;function u(e,t){try{e.processMessage(t)}catch(e){l(e)}}function d(e,i){r.addLast({handler:e,msg:i}),null===t&&(t=n(h))}function h(){if(t=null,r.isEmpty)return;let e={handler:null,msg:null};for(r.addLast(e);;){let t=r.removeFirst();if(t===e)return;t.handler&&t.msg&&s(t.handler,t.msg)}}function p(e){0===a.size&&n(f),a.add(e)}function f(){a.forEach(m),a.clear()}function m(e){D.removeAllWhere(e,g)}function g(e){return null===e}}(B||(B={}));class W{constructor(e){this._pid=R.nextPID(),this.name=e.name,this._create=e.create,this._coerce=e.coerce||null,this._compare=e.compare||null,this._changed=e.changed||null}get(e){let t,n=R.ensureMap(e);return t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e),t}set(e,t){let n,i=R.ensureMap(e);n=this._pid in i?i[this._pid]:i[this._pid]=this._createValue(e);let s=this._coerceValue(e,t);this._maybeNotify(e,n,i[this._pid]=s)}coerce(e){let t,n=R.ensureMap(e);t=this._pid in n?n[this._pid]:n[this._pid]=this._createValue(e);let i=this._coerceValue(e,t);this._maybeNotify(e,t,n[this._pid]=i)}_createValue(e){return(0,this._create)(e)}_coerceValue(e,t){let n=this._coerce;return n?n(e,t):t}_compareValue(e,t){let n=this._compare;return n?n(e,t):e===t}_maybeNotify(e,t,n){let i=this._changed;i&&!this._compareValue(t,n)&&i(e,t,n)}}!function(e){e.clearData=function(e){R.ownerData.delete(e)}}(W||(W={})),function(e){e.ownerData=new WeakMap,e.nextPID=(()=>{let e=0;return()=>`pid-${`${Math.random()}`.slice(2)}-${e++}`})(),e.ensureMap=function(t){let n=e.ownerData.get(t);return n||(n=Object.create(null),e.ownerData.set(t,n),n)}}(R||(R={}));class H{constructor(e){this.sender=e}connect(e,t){return T.connect(this,e,t)}disconnect(e,t){return T.disconnect(this,e,t)}emit(e){T.emit(this,e)}}(j=H||(H={})).disconnectBetween=function(e,t){T.disconnectBetween(e,t)},j.disconnectSender=function(e){T.disconnectSender(e)},j.disconnectReceiver=function(e){T.disconnectReceiver(e)},j.disconnectAll=function(e){T.disconnectAll(e)},j.clearData=function(e){T.disconnectAll(e)},j.getExceptionHandler=function(){return T.exceptionHandler},j.setExceptionHandler=function(e){let t=T.exceptionHandler;return T.exceptionHandler=e,t};class K extends(null){constructor(){super(...arguments),this._pending=new PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new PromiseDelegate}}!function(e){function t(e){let t=i.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,c(s.get(t))}c(t)}}function n(e){let t=s.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,c(i.get(t))}c(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let r=i.get(e.sender);if(r||(r=[],i.set(e.sender,r)),a(r,e,t,n))return!1;let o=n||t,l=s.get(o);l||(l=[],s.set(o,l));let c={signal:e,slot:t,thisArg:n};return r.push(c),l.push(c),!0},e.disconnect=function(e,t,n){n=n||void 0;let r=i.get(e.sender);if(!r||0===r.length)return!1;let o=a(r,e,t,n);if(!o)return!1;let l=n||t,u=s.get(l);return o.signal=null,c(r),c(u),!0},e.disconnectBetween=function(e,t){let n=i.get(e);if(!n||0===n.length)return;let r=s.get(t);if(r&&0!==r.length){for(const t of r)t.signal&&t.signal.sender===e&&(t.signal=null);c(n),c(r)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=i.get(e.sender);if(n&&0!==n.length)for(let i=0,s=n.length;ie.signal===t&&e.slot===n&&e.thisArg===i))}function l(t,n){let{signal:i,slot:s,thisArg:r}=t;try{s.call(r,i.sender,n)}catch(t){e.exceptionHandler(t)}}function c(e){0===r.size&&o(u),r.add(e)}function u(){r.forEach(d),r.clear()}function d(e){D.removeAllWhere(e,h)}function h(e){return null===e.signal}}(T||(T={}));class ${constructor(e){this._fn=e}get isDisposed(){return!this._fn}dispose(){if(!this._fn)return;let e=this._fn;this._fn=null,e()}}class V{constructor(){this._isDisposed=!1,this._items=new Set}get isDisposed(){return this._isDisposed}dispose(){this._isDisposed||(this._isDisposed=!0,this._items.forEach((e=>{e.dispose()})),this._items.clear())}contains(e){return this._items.has(e)}add(e){this._items.add(e)}remove(e){this._items.delete(e)}clear(){this._items.clear()}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(V||(V={}));class J extends V{constructor(){super(...arguments),this._disposed=new H(this)}get disposed(){return this._disposed}dispose(){this.isDisposed||(super.dispose(),this._disposed.emit(void 0),H.clearData(this))}}!function(e){e.from=function(t){let n=new e;for(const e of t)n.add(e);return n}}(J||(J={}));class G{constructor(e){this._onScrollFrame=()=>{if(!this._scrollTarget)return;let{element:e,edge:t,distance:n}=this._scrollTarget,i=L.SCROLL_EDGE_SIZE-n,s=Math.pow(i/L.SCROLL_EDGE_SIZE,2),r=Math.max(1,Math.round(s*L.SCROLL_EDGE_SIZE));switch(t){case"top":e.scrollTop-=r;break;case"left":e.scrollLeft-=r;break;case"right":e.scrollLeft+=r;break;case"bottom":e.scrollTop+=r}requestAnimationFrame(this._onScrollFrame)},this._disposed=!1,this._dropAction="none",this._override=null,this._currentTarget=null,this._currentElement=null,this._promise=null,this._scrollTarget=null,this._resolve=null,this.document=e.document||document,this.mimeData=e.mimeData,this.dragImage=e.dragImage||null,this.proposedAction=e.proposedAction||"copy",this.supportedActions=e.supportedActions||"all",this.source=e.source||null}dispose(){if(!this._disposed){if(this._disposed=!0,this._currentTarget){let e=new PointerEvent("pointerup",{bubbles:!0,cancelable:!0,clientX:-1,clientY:-1});L.dispatchDragLeave(this,this._currentTarget,null,e)}this._finalize("none")}}get isDisposed(){return this._disposed}start(e,t){if(this._disposed)return Promise.resolve("none");if(this._promise)return this._promise;this._addListeners(),this._attachDragImage(e,t),this._promise=new Promise((e=>{this._resolve=e}));let n=new PointerEvent("pointermove",{bubbles:!0,cancelable:!0,clientX:e,clientY:t});return document.dispatchEvent(n),this._promise}handleEvent(e){switch(e.type){case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;default:e.preventDefault(),e.stopPropagation()}}moveDragImage(e,t){this.dragImage&&(this.dragImage.style.transform=`translate(${e}px, ${t}px)`)}_evtPointerMove(e){e.preventDefault(),e.stopPropagation(),this._updateCurrentTarget(e),this._updateDragScroll(e),this.moveDragImage(e.clientX,e.clientY)}_evtPointerUp(e){if(e.preventDefault(),e.stopPropagation(),0!==e.button)return;if(this._updateCurrentTarget(e),!this._currentTarget)return void this._finalize("none");if("none"===this._dropAction)return L.dispatchDragLeave(this,this._currentTarget,null,e),void this._finalize("none");let t=L.dispatchDrop(this,this._currentTarget,e);this._finalize(t)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation(),27===e.keyCode&&this.dispose()}_addListeners(){document.addEventListener("pointerdown",this,!0),document.addEventListener("pointermove",this,!0),document.addEventListener("pointerup",this,!0),document.addEventListener("pointerenter",this,!0),document.addEventListener("pointerleave",this,!0),document.addEventListener("pointerover",this,!0),document.addEventListener("pointerout",this,!0),document.addEventListener("keydown",this,!0),document.addEventListener("keyup",this,!0),document.addEventListener("keypress",this,!0),document.addEventListener("contextmenu",this,!0)}_removeListeners(){document.removeEventListener("pointerdown",this,!0),document.removeEventListener("pointermove",this,!0),document.removeEventListener("pointerup",this,!0),document.removeEventListener("pointerenter",this,!0),document.removeEventListener("pointerleave",this,!0),document.removeEventListener("pointerover",this,!0),document.removeEventListener("pointerout",this,!0),document.removeEventListener("keydown",this,!0),document.removeEventListener("keyup",this,!0),document.removeEventListener("keypress",this,!0),document.removeEventListener("contextmenu",this,!0)}_updateDragScroll(e){let t=L.findScrollTarget(e);(this._scrollTarget||t)&&(this._scrollTarget||setTimeout(this._onScrollFrame,500),this._scrollTarget=t)}_updateCurrentTarget(e){let t=this._currentTarget,n=this._currentTarget,i=this._currentElement,s=L.findElementBehindBackdrop(e,this.document);this._currentElement=s,s!==i&&s!==n&&L.dispatchDragExit(this,n,s,e),s!==i&&s!==n&&(n=L.dispatchDragEnter(this,s,n,e)),n!==t&&(this._currentTarget=n,L.dispatchDragLeave(this,t,n,e));let r=L.dispatchDragOver(this,n,e);this._setDropAction(r)}_attachDragImage(e,t){if(!this.dragImage)return;this.dragImage.classList.add("lm-mod-drag-image");let n=this.dragImage.style;n.pointerEvents="none",n.position="fixed",n.transform=`translate(${e}px, ${t}px)`,(this.document instanceof Document?this.document.body:this.document.firstElementChild).appendChild(this.dragImage)}_detachDragImage(){if(!this.dragImage)return;let e=this.dragImage.parentNode;e&&e.removeChild(this.dragImage)}_setDropAction(e){if(e=L.validateAction(e,this.supportedActions),!this._override||this._dropAction!==e)switch(e){case"none":this._dropAction=e,this._override=G.overrideCursor("no-drop",this.document);break;case"copy":this._dropAction=e,this._override=G.overrideCursor("copy",this.document);break;case"link":this._dropAction=e,this._override=G.overrideCursor("alias",this.document);break;case"move":this._dropAction=e,this._override=G.overrideCursor("move",this.document)}}_finalize(e){let t=this._resolve;this._removeListeners(),this._detachDragImage(),this._override&&(this._override.dispose(),this._override=null),this.mimeData.clear(),this._disposed=!0,this._dropAction="none",this._currentTarget=null,this._currentElement=null,this._scrollTarget=null,this._promise=null,this._resolve=null,t&&t(e)}}function Y(){return Q.keyboardLayout}!function(e){class t extends DragEvent{constructor(e,t){super(t.type,{bubbles:!0,cancelable:!0,altKey:e.altKey,button:e.button,clientX:e.clientX,clientY:e.clientY,ctrlKey:e.ctrlKey,detail:0,metaKey:e.metaKey,relatedTarget:t.related,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window});const{drag:n}=t;this.dropAction="none",this.mimeData=n.mimeData,this.proposedAction=n.proposedAction,this.supportedActions=n.supportedActions,this.source=n.source}}e.Event=t,e.overrideCursor=function(e,t=document){return L.overrideCursor(e,t)}}(G||(G={})),function(e){function t(t,s=document){if(t){if(n&&t==n.event)return n.element;e.cursorBackdrop.style.zIndex="-1000";const i=s.elementFromPoint(t.clientX,t.clientY);return e.cursorBackdrop.style.zIndex="",n={event:t,element:i},i}{const t=e.cursorBackdrop.style.transform;if(i&&t===i.transform)return i.element;const n=e.cursorBackdrop.getBoundingClientRect();e.cursorBackdrop.style.zIndex="-1000";const r=s.elementFromPoint(n.left+n.width/2,n.top+n.height/2);return e.cursorBackdrop.style.zIndex="",i={transform:t,element:r},r}}e.SCROLL_EDGE_SIZE=20,e.validateAction=function(e,t){return s[e]&r[t]?e:"none"},e.findElementBehindBackdrop=t;let n=null,i=null;e.findScrollTarget=function(n){let i=n.clientX,s=n.clientY,r=t(n);for(;r;r=r.parentElement){if(!r.hasAttribute("data-lm-dragscroll"))continue;let t=0,n=0;r===document.body&&(t=window.pageXOffset,n=window.pageYOffset);let o=r.getBoundingClientRect(),a=o.top+n,l=o.left+t,c=l+o.width,u=a+o.height;if(i=c||s=u)continue;let d,h=i-l+1,p=s-a+1,f=c-i,m=u-s,g=Math.min(h,p,f,m);if(g>e.SCROLL_EDGE_SIZE)continue;switch(g){case m:d="bottom";break;case p:d="top";break;case f:d="right";break;case h:d="left";break;default:throw"unreachable"}let v,_=r.scrollWidth-r.clientWidth,y=r.scrollHeight-r.clientHeight;switch(d){case"top":v=y>0&&r.scrollTop>0;break;case"left":v=_>0&&r.scrollLeft>0;break;case"right":v=_>0&&r.scrollLeft<_;break;case"bottom":v=y>0&&r.scrollTop{i===u&&e.cursorBackdrop.isConnected&&(document.removeEventListener("pointermove",o,!0),e.cursorBackdrop.removeEventListener("scroll",a,!0),s.removeChild(e.cursorBackdrop))}))};const c=500;let u=0;e.cursorBackdrop=function(){const e=document.createElement("div");return e.classList.add("lm-cursor-backdrop"),e}()}(L||(L={}));class X{constructor(e,t,n=[]){this.name=e,this._codes=t,this._keys=X.extractKeys(t),this._modifierKeys=X.convertToKeySet(n)}keys(){return Object.keys(this._keys)}isValidKey(e){return e in this._keys}isModifierKey(e){return e in this._modifierKeys}keyForKeydownEvent(e){return this._codes[e.keyCode]||""}}!function(e){e.extractKeys=function(e){let t=Object.create(null);for(let n in e)t[e[n]]=!0;return t},e.convertToKeySet=function(e){let t=Object(null);for(let n=0,i=e.length;n{this._commands.delete(e),this._commandChanged.emit({id:e,type:"removed"})}))}notifyCommandChanged(e){if(void 0!==e&&!this._commands.has(e))throw new Error(`Command '${e}' is not registered.`);this._commandChanged.emit({id:e,type:e?"changed":"many-changed"})}describedBy(e,t=N.JSONExt.emptyObject){var n;let i=this._commands.get(e);return Promise.resolve(null!==(n=null==i?void 0:i.describedBy.call(void 0,t))&&void 0!==n?n:{args:null})}label(e,t=N.JSONExt.emptyObject){var n;let i=this._commands.get(e);return null!==(n=null==i?void 0:i.label.call(void 0,t))&&void 0!==n?n:""}mnemonic(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.mnemonic.call(void 0,t):-1}icon(e,t=N.JSONExt.emptyObject){var n;return null===(n=this._commands.get(e))||void 0===n?void 0:n.icon.call(void 0,t)}iconClass(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconClass.call(void 0,t):""}iconLabel(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.iconLabel.call(void 0,t):""}caption(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.caption.call(void 0,t):""}usage(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.usage.call(void 0,t):""}className(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.className.call(void 0,t):""}dataset(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return n?n.dataset.call(void 0,t):{}}isEnabled(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isEnabled.call(void 0,t)}isToggled(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggled.call(void 0,t)}isToggleable(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isToggleable}isVisible(e,t=N.JSONExt.emptyObject){let n=this._commands.get(e);return!!n&&n.isVisible.call(void 0,t)}execute(e,t=N.JSONExt.emptyObject){let n,i=this._commands.get(e);if(!i)return Promise.reject(new Error(`Command '${e}' not registered.`));try{n=i.execute.call(void 0,t)}catch(e){n=Promise.reject(e)}let s=Promise.resolve(n);return this._commandExecuted.emit({id:e,args:t,result:s}),s}addKeyBinding(e){let t=ee.createKeyBinding(e);return this._keyBindings.push(t),this._keyBindingChanged.emit({binding:t,type:"added"}),new $((()=>{D.removeFirstOf(this._keyBindings,t),this._keyBindingChanged.emit({binding:t,type:"removed"})}))}processKeydownEvent(e){if(this._replaying||ae.isModifierKeyPressed(e))return;let t=ae.keystrokeForKeydownEvent(e);if(!t)return this._replayKeydownEvents(),void this._clearPendingState();this._keystrokes.push(t);let{exact:n,partial:i}=ee.matchKeyBinding(this._keyBindings,this._keystrokes,e);return n||i?(e.preventDefault(),e.stopPropagation(),n&&!i?(this._executeKeyBinding(n),void this._clearPendingState()):(n&&(this._exactKeyMatch=n),this._keydownEvents.push(e),void this._startTimer())):(this._replayKeydownEvents(),void this._clearPendingState())}_startTimer(){this._clearTimer(),this._timerID=window.setTimeout((()=>{this._onPendingTimeout()}),ee.CHORD_TIMEOUT)}_clearTimer(){0!==this._timerID&&(clearTimeout(this._timerID),this._timerID=0)}_replayKeydownEvents(){0!==this._keydownEvents.length&&(this._replaying=!0,this._keydownEvents.forEach(ee.replayKeyEvent),this._replaying=!1)}_executeKeyBinding(e){let{command:t,args:n}=e,i={_luminoEvent:{type:"keybinding",keys:e.keys},...n};if(this.hasCommand(t)&&this.isEnabled(t,i))this.execute(t,i);else{let n=this.hasCommand(t)?"enabled":"registered",i=`Cannot execute key binding '${e.keys.join(", ")}':`,s=`command '${t}' is not ${n}.`;console.warn(`${i} ${s}`)}}_clearPendingState(){this._clearTimer(),this._exactKeyMatch=null,this._keystrokes.length=0,this._keydownEvents.length=0}_onPendingTimeout(){this._timerID=0,this._exactKeyMatch?this._executeKeyBinding(this._exactKeyMatch):this._replayKeydownEvents(),this._clearPendingState()}}!function(e){function t(e){let t="",n=!1,i=!1,s=!1,r=!1;for(let o of e.split(/\s+/))"Accel"===o?F.IS_MAC?i=!0:s=!0:"Alt"===o?n=!0:"Cmd"===o?i=!0:"Ctrl"===o?s=!0:"Shift"===o?r=!0:o.length>0&&(t=o);return{cmd:i,ctrl:s,alt:n,shift:r,key:t}}function n(e){let n="",i=t(e);return i.ctrl&&(n+="Ctrl "),i.alt&&(n+="Alt "),i.shift&&(n+="Shift "),i.cmd&&F.IS_MAC&&(n+="Cmd "),n+i.key}e.parseKeystroke=t,e.normalizeKeystroke=n,e.normalizeKeys=function(e){let t;return t=F.IS_WIN?e.winKeys||e.keys:F.IS_MAC?e.macKeys||e.keys:e.linuxKeys||e.keys,t.map(n)},e.formatKeystroke=function(e){return"string"==typeof e?n(e):e.map(n).join(", ");function n(e){let n=[],i=F.IS_MAC?" ":"+",s=t(e);return s.ctrl&&n.push("Ctrl"),s.alt&&n.push("Alt"),s.shift&&n.push("Shift"),F.IS_MAC&&s.cmd&&n.push("Cmd"),n.push(s.key),n.map(ee.formatKey).join(i)}},e.isModifierKeyPressed=function(e){let t=Y(),n=t.keyForKeydownEvent(e);return t.isModifierKey(n)},e.keystrokeForKeydownEvent=function(e){let t=Y(),n=t.keyForKeydownEvent(e);if(!n||t.isModifierKey(n))return"";let i=[];return e.ctrlKey&&i.push("Ctrl"),e.altKey&&i.push("Alt"),e.shiftKey&&i.push("Shift"),e.metaKey&&F.IS_MAC&&i.push("Cmd"),i.push(n),i.join(" ")}}(ae||(ae={})),function(e){e.CHORD_TIMEOUT=1e3,e.createCommand=function(e){return{execute:e.execute,describedBy:c("function"==typeof e.describedBy?e.describedBy:{args:null,...e.describedBy},(()=>({args:null}))),label:c(e.label,i),mnemonic:c(e.mnemonic,s),icon:c(e.icon,l),iconClass:c(e.iconClass,i),iconLabel:c(e.iconLabel,i),caption:c(e.caption,i),usage:c(e.usage,i),className:c(e.className,i),dataset:c(e.dataset,a),isEnabled:e.isEnabled||r,isToggled:e.isToggled||o,isToggleable:e.isToggleable||!!e.isToggled,isVisible:e.isVisible||r}},e.createKeyBinding=function(e){return{keys:ae.normalizeKeys(e),selector:u(e),command:e.command,args:e.args||N.JSONExt.emptyObject}},e.matchKeyBinding=function(e,t,n){let i=null,s=!1,r=1/0,o=0;for(let a=0,l=e.length;ar)continue;let p=I.calculateSpecificity(l.selector);(!i||u=o)&&(i=l,r=u,o=p)}return{exact:i,partial:s}},e.replayKeyEvent=function(e){e.target.dispatchEvent(function(e){let t=document.createEvent("Event"),n=e.bubbles||!0,i=e.cancelable||!0;return t.initEvent(e.type||"keydown",n,i),t.key=e.key||"",t.keyCode=e.keyCode||0,t.which=e.keyCode||0,t.ctrlKey=e.ctrlKey||!1,t.altKey=e.altKey||!1,t.shiftKey=e.shiftKey||!1,t.metaKey=e.metaKey||!1,t.view=e.view||window,t}(e))},e.formatKey=function(e){return F.IS_MAC?t.hasOwnProperty(e)?t[e]:e:n.hasOwnProperty(e)?n[e]:e};const t={Backspace:"⌫",Tab:"⇥",Enter:"⏎",Shift:"⇧",Ctrl:"⌃",Alt:"⌥",Escape:"⎋",PageUp:"⇞",PageDown:"⇟",End:"↘",Home:"↖",ArrowLeft:"←",ArrowUp:"↑",ArrowRight:"→",ArrowDown:"↓",Delete:"⌦",Cmd:"⌘"},n={Escape:"Esc",PageUp:"Page Up",PageDown:"Page Down",ArrowLeft:"Left",ArrowUp:"Up",ArrowRight:"Right",ArrowDown:"Down",Delete:"Del"},i=()=>"",s=()=>-1,r=()=>!0,o=()=>!1,a=()=>({}),l=()=>{};function c(e,t){return void 0===e?t:"function"==typeof e?e:()=>e}function u(e){if(-1!==e.selector.indexOf(","))throw new Error(`Selector cannot contain commas: ${e.selector}`);if(!I.isValid(e.selector))throw new Error(`Invalid selector: ${e.selector}`);return e.selector}function d(e,t){if(e.lengtht.length?2:1}function h(e,t){let n=t.target,i=t.currentTarget;for(let t=0;null!==n;n=n.parentElement,++t){if(n.hasAttribute("data-lm-suppress-shortcuts"))return-1;if(I.matches(n,e))return t;if(n===i)return-1}return-1}}(ee||(ee={}));class le{constructor(e){this.type="text",this.content=e}}class ce{constructor(e,t,n,i){this.type="element",this.tag=e,this.attrs=t,this.children=n,this.renderer=i}}function ue(e){let t,n={},i=[];for(let e=1,r=arguments.length;e=i;--r){const i=t[r],o=s?e.lastChild:e.childNodes[r];"text"===i.type||(i.renderer&&i.renderer.unrender?i.renderer.unrender(o,{attrs:i.attrs,children:i.children}):n(o,i.children,0,!1)),s&&e.removeChild(o)}}e.hostMap=new WeakMap,e.asContentArray=function(e){return e?e instanceof Array?e:[e]:[]},e.createDOMNode=t,e.updateContent=function e(i,r,o){if(r===o)return;let a=function(e,t){let n=e.firstChild,i=Object.create(null);for(let e of t)"element"===e.type&&e.attrs.key&&(i[e.attrs.key]={vNode:e,element:n}),n=n.nextSibling;return i}(i,r),l=r.slice(),c=i.firstChild,u=o.length;for(let n=0;n=l.length){t(o[n],i);continue}let r=l[n],u=o[n];if(r===u){c=c.nextSibling;continue}if("text"===r.type&&"text"===u.type){c.textContent!==u.content&&(c.textContent=u.content),c=c.nextSibling;continue}if("text"===r.type||"text"===u.type){D.insert(l,n,u),t(u,i,c);continue}if(!r.renderer!=!u.renderer){D.insert(l,n,u),t(u,i,c);continue}let d=u.attrs.key;if(d&&d in a){let e=a[d];e.vNode!==r&&(D.move(l,l.indexOf(e.vNode,n+1),n),i.insertBefore(e.element,c),r=e.vNode,c=e.element)}if(r===u){c=c.nextSibling;continue}let h=r.attrs.key;h&&h!==d?(D.insert(l,n,u),t(u,i,c)):r.tag===u.tag?(s(c,r.attrs,u.attrs),u.renderer?u.renderer.render(c,{attrs:u.attrs,children:u.children}):e(c,r.children,u.children),c=c.nextSibling):(D.insert(l,n,u),t(u,i,c))}n(i,l,u,!0)};const i={key:!0,className:!0,htmlFor:!0,dataset:!0,style:!0};function s(e,t,n){if(t===n)return;let s;for(s in t)s in i||s in n||("on"===s.substr(0,2)?e[s]=null:e.removeAttribute(s));for(s in n)s in i||t[s]===n[s]||("on"===s.substr(0,2)?e[s]=n[s]:e.setAttribute(s,n[s]));t.className!==n.className&&(void 0!==n.className?e.setAttribute("class",n.className):e.removeAttribute("class")),t.htmlFor!==n.htmlFor&&(void 0!==n.htmlFor?e.setAttribute("for",n.htmlFor):e.removeAttribute("for")),t.dataset!==n.dataset&&function(e,t,n){for(let i in t)i in n||e.removeAttribute(`data-${i}`);for(let i in n)t[i]!==n[i]&&e.setAttribute(`data-${i}`,n[i])}(e,t.dataset||{},n.dataset||{}),t.style!==n.style&&function(e,t,n){let i,s=e.style;for(i in t)i in n||(s[i]="");for(i in n)t[i]!==n[i]&&(s[i]=n[i])}(e,t.style||{},n.style||{})}}(ne||(ne={}));class de{constructor(){this.sizeHint=0,this.minSize=0,this.maxSize=1/0,this.stretch=1,this.size=0,this.done=!1}}!function(e){e.calc=function(e,t){let n=e.length;if(0===n)return t;let i=0,s=0,r=0,o=0,a=0;for(let t=0;t0&&(o+=n.stretch,a++)}if(t===r)return 0;if(t<=i){for(let t=0;t=s){for(let t=0;t0&&i>l;){let t=i,s=o;for(let r=0;r0&&i>l;){let t=i/c;for(let s=0;s0&&i>l;){let t=i,s=o;for(let r=0;r=n.maxSize?(i-=n.maxSize-n.size,o-=n.stretch,n.size=n.maxSize,n.done=!0,c--,a--):(i-=l,n.size+=l)}}for(;c>0&&i>l;){let t=i/c;for(let s=0;s=n.maxSize?(i-=n.maxSize-n.size,n.size=n.maxSize,n.done=!0,c--):(i-=t,n.size+=t))}}}return 0},e.adjust=function(e,t,n){0!==e.length&&0!==n&&(n>0?function(e,t,n){let i=0;for(let n=0;n<=t;++n){let t=e[n];i+=t.maxSize-t.size}let s=0;for(let n=t+1,i=e.length;n=0&&r>0;--n){let t=e[n],i=t.maxSize-t.size;i>=r?(t.sizeHint=t.size+r,r=0):(t.sizeHint=t.size+i,r-=i)}let o=n;for(let n=t+1,i=e.length;n0;++n){let t=e[n],i=t.size-t.minSize;i>=o?(t.sizeHint=t.size-o,o=0):(t.sizeHint=t.size-i,o-=i)}}(e,t,n):function(e,t,n){let i=0;for(let n=t+1,s=e.length;n0;++n){let t=e[n],i=t.maxSize-t.size;i>=r?(t.sizeHint=t.size+r,r=0):(t.sizeHint=t.size+i,r-=i)}let o=n;for(let n=t;n>=0&&o>0;--n){let t=e[n],i=t.size-t.minSize;i>=o?(t.sizeHint=t.size-o,o=0):(t.sizeHint=t.size-i,o-=i)}}(e,t,-n))}}(ie||(ie={}));class he{constructor(e){this._label="",this._caption="",this._mnemonic=-1,this._icon=void 0,this._iconClass="",this._iconLabel="",this._className="",this._closable=!1,this._changed=new H(this),this._isDisposed=!1,this.owner=e.owner,void 0!==e.label&&(this._label=e.label),void 0!==e.mnemonic&&(this._mnemonic=e.mnemonic),void 0!==e.icon&&(this._icon=e.icon),void 0!==e.iconClass&&(this._iconClass=e.iconClass),void 0!==e.iconLabel&&(this._iconLabel=e.iconLabel),void 0!==e.caption&&(this._caption=e.caption),void 0!==e.className&&(this._className=e.className),void 0!==e.closable&&(this._closable=e.closable),this._dataset=e.dataset||{}}get changed(){return this._changed}get label(){return this._label}set label(e){this._label!==e&&(this._label=e,this._changed.emit(void 0))}get mnemonic(){return this._mnemonic}set mnemonic(e){this._mnemonic!==e&&(this._mnemonic=e,this._changed.emit(void 0))}get icon(){return this._icon}set icon(e){this._icon!==e&&(this._icon=e,this._changed.emit(void 0))}get iconClass(){return this._iconClass}set iconClass(e){this._iconClass!==e&&(this._iconClass=e,this._changed.emit(void 0))}get iconLabel(){return this._iconLabel}set iconLabel(e){this._iconLabel!==e&&(this._iconLabel=e,this._changed.emit(void 0))}get caption(){return this._caption}set caption(e){this._caption!==e&&(this._caption=e,this._changed.emit(void 0))}get className(){return this._className}set className(e){this._className!==e&&(this._className=e,this._changed.emit(void 0))}get closable(){return this._closable}set closable(e){this._closable!==e&&(this._closable=e,this._changed.emit(void 0))}get dataset(){return this._dataset}set dataset(e){this._dataset!==e&&(this._dataset=e,this._changed.emit(void 0))}get isDisposed(){return this._isDisposed}dispose(){this.isDisposed||(this._isDisposed=!0,H.clearData(this))}}class pe{constructor(e={}){this._flags=0,this._layout=null,this._parent=null,this._disposed=new H(this),this._hiddenMode=pe.HiddenMode.Display,this.node=se.createNode(e),this.addClass("lm-Widget")}dispose(){this.isDisposed||(this.setFlag(pe.Flag.IsDisposed),this._disposed.emit(void 0),this.parent?this.parent=null:this.isAttached&&pe.detach(this),this._layout&&(this._layout.dispose(),this._layout=null),this.title.dispose(),H.clearData(this),B.clearData(this),W.clearData(this))}get disposed(){return this._disposed}get isDisposed(){return this.testFlag(pe.Flag.IsDisposed)}get isAttached(){return this.testFlag(pe.Flag.IsAttached)}get isHidden(){return this.testFlag(pe.Flag.IsHidden)}get isVisible(){return this.testFlag(pe.Flag.IsVisible)}get title(){return se.titleProperty.get(this)}get id(){return this.node.id}set id(e){this.node.id=e}get dataset(){return this.node.dataset}get hiddenMode(){return this._hiddenMode}set hiddenMode(e){this._hiddenMode!==e&&(this.isHidden&&this._toggleHidden(!1),e==pe.HiddenMode.Scale?this.node.style.willChange="transform":this.node.style.willChange="auto",this._hiddenMode=e,this.isHidden&&this._toggleHidden(!0))}get parent(){return this._parent}set parent(e){if(this._parent!==e){if(e&&this.contains(e))throw new Error("Invalid parent widget.");if(this._parent&&!this._parent.isDisposed){let e=new pe.ChildMessage("child-removed",this);B.sendMessage(this._parent,e)}if(this._parent=e,this._parent&&!this._parent.isDisposed){let e=new pe.ChildMessage("child-added",this);B.sendMessage(this._parent,e)}this.isDisposed||B.sendMessage(this,pe.Msg.ParentChanged)}}get layout(){return this._layout}set layout(e){if(this._layout!==e){if(this.testFlag(pe.Flag.DisallowLayout))throw new Error("Cannot set widget layout.");if(this._layout)throw new Error("Cannot change widget layout.");if(e.parent)throw new Error("Cannot change layout parent.");this._layout=e,e.parent=this}}*children(){this._layout&&(yield*this._layout)}contains(e){for(let t=e;t;t=t._parent)if(t===this)return!0;return!1}hasClass(e){return this.node.classList.contains(e)}addClass(e){this.node.classList.add(e)}removeClass(e){this.node.classList.remove(e)}toggleClass(e,t){return!0===t?(this.node.classList.add(e),!0):!1===t?(this.node.classList.remove(e),!1):this.node.classList.toggle(e)}update(){B.postMessage(this,pe.Msg.UpdateRequest)}fit(){B.postMessage(this,pe.Msg.FitRequest)}activate(){B.postMessage(this,pe.Msg.ActivateRequest)}close(){B.sendMessage(this,pe.Msg.CloseRequest)}show(){if(this.testFlag(pe.Flag.IsHidden)&&(!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.BeforeShow),this.clearFlag(pe.Flag.IsHidden),this._toggleHidden(!1),!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.AfterShow),this.parent)){let e=new pe.ChildMessage("child-shown",this);B.sendMessage(this.parent,e)}}hide(){if(!this.testFlag(pe.Flag.IsHidden)&&(!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.BeforeHide),this.setFlag(pe.Flag.IsHidden),this._toggleHidden(!0),!this.isAttached||this.parent&&!this.parent.isVisible||B.sendMessage(this,pe.Msg.AfterHide),this.parent)){let e=new pe.ChildMessage("child-hidden",this);B.sendMessage(this.parent,e)}}setHidden(e){e?this.hide():this.show()}testFlag(e){return 0!=(this._flags&e)}setFlag(e){this._flags|=e}clearFlag(e){this._flags&=~e}processMessage(e){switch(e.type){case"resize":this.notifyLayout(e),this.onResize(e);break;case"update-request":this.notifyLayout(e),this.onUpdateRequest(e);break;case"fit-request":this.notifyLayout(e),this.onFitRequest(e);break;case"before-show":this.notifyLayout(e),this.onBeforeShow(e);break;case"after-show":this.setFlag(pe.Flag.IsVisible),this.notifyLayout(e),this.onAfterShow(e);break;case"before-hide":this.notifyLayout(e),this.onBeforeHide(e);break;case"after-hide":this.clearFlag(pe.Flag.IsVisible),this.notifyLayout(e),this.onAfterHide(e);break;case"before-attach":this.notifyLayout(e),this.onBeforeAttach(e);break;case"after-attach":this.isHidden||this.parent&&!this.parent.isVisible||this.setFlag(pe.Flag.IsVisible),this.setFlag(pe.Flag.IsAttached),this.notifyLayout(e),this.onAfterAttach(e);break;case"before-detach":this.notifyLayout(e),this.onBeforeDetach(e);break;case"after-detach":this.clearFlag(pe.Flag.IsVisible),this.clearFlag(pe.Flag.IsAttached),this.notifyLayout(e),this.onAfterDetach(e);break;case"activate-request":this.notifyLayout(e),this.onActivateRequest(e);break;case"close-request":this.notifyLayout(e),this.onCloseRequest(e);break;case"child-added":this.notifyLayout(e),this.onChildAdded(e);break;case"child-removed":this.notifyLayout(e),this.onChildRemoved(e);break;default:this.notifyLayout(e)}}notifyLayout(e){this._layout&&this._layout.processParentMessage(e)}onCloseRequest(e){this.parent?this.parent=null:this.isAttached&&pe.detach(this)}onResize(e){}onUpdateRequest(e){}onFitRequest(e){}onActivateRequest(e){}onBeforeShow(e){}onAfterShow(e){}onBeforeHide(e){}onAfterHide(e){}onBeforeAttach(e){}onAfterAttach(e){}onBeforeDetach(e){}onAfterDetach(e){}onChildAdded(e){}onChildRemoved(e){}_toggleHidden(e){if(e)switch(this._hiddenMode){case pe.HiddenMode.Display:this.addClass("lm-mod-hidden");break;case pe.HiddenMode.Scale:this.node.style.transform="scale(0)",this.node.setAttribute("aria-hidden","true");break;case pe.HiddenMode.ContentVisibility:this.node.style.contentVisibility="hidden",this.node.style.zIndex="-1"}else switch(this._hiddenMode){case pe.HiddenMode.Display:this.removeClass("lm-mod-hidden");break;case pe.HiddenMode.Scale:this.node.style.transform="",this.node.removeAttribute("aria-hidden");break;case pe.HiddenMode.ContentVisibility:this.node.style.contentVisibility="",this.node.style.zIndex=""}}}!function(e){var t,n,i;(t=e.HiddenMode||(e.HiddenMode={}))[t.Display=0]="Display",t[t.Scale=1]="Scale",t[t.ContentVisibility=2]="ContentVisibility",(n=e.Flag||(e.Flag={}))[n.IsDisposed=1]="IsDisposed",n[n.IsAttached=2]="IsAttached",n[n.IsHidden=4]="IsHidden",n[n.IsVisible=8]="IsVisible",n[n.DisallowLayout=16]="DisallowLayout",(i=e.Msg||(e.Msg={})).BeforeShow=new U("before-show"),i.AfterShow=new U("after-show"),i.BeforeHide=new U("before-hide"),i.AfterHide=new U("after-hide"),i.BeforeAttach=new U("before-attach"),i.AfterAttach=new U("after-attach"),i.BeforeDetach=new U("before-detach"),i.AfterDetach=new U("after-detach"),i.ParentChanged=new U("parent-changed"),i.UpdateRequest=new q("update-request"),i.FitRequest=new q("fit-request"),i.ActivateRequest=new q("activate-request"),i.CloseRequest=new q("close-request"),e.ChildMessage=class extends U{constructor(e,t){super(e),this.child=t}};class s extends U{constructor(e,t){super("resize"),this.width=e,this.height=t}}e.ResizeMessage=s,function(e){e.UnknownSize=new e(-1,-1)}(s=e.ResizeMessage||(e.ResizeMessage={})),e.attach=function(t,n,i=null){if(t.parent)throw new Error("Cannot attach a child widget.");if(t.isAttached||t.node.isConnected)throw new Error("Widget is already attached.");if(!n.isConnected)throw new Error("Host is not attached.");B.sendMessage(t,e.Msg.BeforeAttach),n.insertBefore(t.node,i),B.sendMessage(t,e.Msg.AfterAttach)},e.detach=function(t){if(t.parent)throw new Error("Cannot detach a child widget.");if(!t.isAttached||!t.node.isConnected)throw new Error("Widget is not attached.");B.sendMessage(t,e.Msg.BeforeDetach),t.node.parentNode.removeChild(t.node),B.sendMessage(t,e.Msg.AfterDetach)}}(pe||(pe={})),function(e){e.titleProperty=new W({name:"title",create:e=>new he({owner:e})}),e.createNode=function(e){return e.node||document.createElement(e.tag||"div")}}(se||(se={}));class fe{constructor(e={}){this._disposed=!1,this._parent=null,this._fitPolicy=e.fitPolicy||"set-min-size"}dispose(){this._parent=null,this._disposed=!0,H.clearData(this),W.clearData(this)}get isDisposed(){return this._disposed}get parent(){return this._parent}set parent(e){if(this._parent!==e){if(this._parent)throw new Error("Cannot change parent widget.");if(e.layout!==this)throw new Error("Invalid parent widget.");this._parent=e,this.init()}}get fitPolicy(){return this._fitPolicy}set fitPolicy(e){if(this._fitPolicy!==e&&(this._fitPolicy=e,this._parent)){let e=this._parent.node.style;e.minWidth="",e.minHeight="",e.maxWidth="",e.maxHeight="",this._parent.fit()}}processParentMessage(e){switch(e.type){case"resize":this.onResize(e);break;case"update-request":this.onUpdateRequest(e);break;case"fit-request":this.onFitRequest(e);break;case"before-show":this.onBeforeShow(e);break;case"after-show":this.onAfterShow(e);break;case"before-hide":this.onBeforeHide(e);break;case"after-hide":this.onAfterHide(e);break;case"before-attach":this.onBeforeAttach(e);break;case"after-attach":this.onAfterAttach(e);break;case"before-detach":this.onBeforeDetach(e);break;case"after-detach":this.onAfterDetach(e);break;case"child-removed":this.onChildRemoved(e);break;case"child-shown":this.onChildShown(e);break;case"child-hidden":this.onChildHidden(e)}}init(){for(const e of this)e.parent=this.parent}onResize(e){for(const e of this)B.sendMessage(e,pe.ResizeMessage.UnknownSize)}onUpdateRequest(e){for(const e of this)B.sendMessage(e,pe.ResizeMessage.UnknownSize)}onBeforeAttach(e){for(const t of this)B.sendMessage(t,e)}onAfterAttach(e){for(const t of this)B.sendMessage(t,e)}onBeforeDetach(e){for(const t of this)B.sendMessage(t,e)}onAfterDetach(e){for(const t of this)B.sendMessage(t,e)}onBeforeShow(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onAfterShow(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onBeforeHide(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onAfterHide(e){for(const t of this)t.isHidden||B.sendMessage(t,e)}onChildRemoved(e){this.removeWidget(e.child)}onFitRequest(e){}onChildShown(e){}onChildHidden(e){}}!function(e){e.getHorizontalAlignment=function(e){return re.horizontalAlignmentProperty.get(e)},e.setHorizontalAlignment=function(e,t){re.horizontalAlignmentProperty.set(e,t)},e.getVerticalAlignment=function(e){return re.verticalAlignmentProperty.get(e)},e.setVerticalAlignment=function(e,t){re.verticalAlignmentProperty.set(e,t)}}(fe||(fe={}));class me{constructor(e){this._top=NaN,this._left=NaN,this._width=NaN,this._height=NaN,this._minWidth=0,this._minHeight=0,this._maxWidth=1/0,this._maxHeight=1/0,this._disposed=!1,this.widget=e,this.widget.node.style.position="absolute",this.widget.node.style.contain="strict"}dispose(){if(this._disposed)return;this._disposed=!0;let e=this.widget.node.style;e.position="",e.top="",e.left="",e.width="",e.height="",e.contain=""}get minWidth(){return this._minWidth}get minHeight(){return this._minHeight}get maxWidth(){return this._maxWidth}get maxHeight(){return this._maxHeight}get isDisposed(){return this._disposed}get isHidden(){return this.widget.isHidden}get isVisible(){return this.widget.isVisible}get isAttached(){return this.widget.isAttached}fit(){let e=M.sizeLimits(this.widget.node);this._minWidth=e.minWidth,this._minHeight=e.minHeight,this._maxWidth=e.maxWidth,this._maxHeight=e.maxHeight}update(e,t,n,i){let s=Math.max(this._minWidth,Math.min(n,this._maxWidth)),r=Math.max(this._minHeight,Math.min(i,this._maxHeight));if(s"center",changed:t}),e.verticalAlignmentProperty=new W({name:"verticalAlignment",create:()=>"top",changed:t})}(re||(re={}));class ge extends fe{constructor(){super(...arguments),this._widgets=[]}dispose(){for(;this._widgets.length>0;)this._widgets.pop().dispose();super.dispose()}get widgets(){return this._widgets}*[Symbol.iterator](){yield*this._widgets}addWidget(e){this.insertWidget(this._widgets.length,e)}insertWidget(e,t){t.parent=this.parent;let n=this._widgets.indexOf(t),i=Math.max(0,Math.min(e,this._widgets.length));if(-1===n)return D.insert(this._widgets,i,t),void(this.parent&&this.attachWidget(i,t));i===this._widgets.length&&i--,n!==i&&(D.move(this._widgets,n,i),this.parent&&this.moveWidget(n,i,t))}removeWidget(e){this.removeWidgetAt(this._widgets.indexOf(e))}removeWidgetAt(e){let t=D.removeAt(this._widgets,e);t&&this.parent&&this.detachWidget(e,t)}init(){super.init();let e=0;for(const t of this)this.attachWidget(e++,t)}attachWidget(e,t){let n=this.parent.node.children[e];this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.insertBefore(t.node,n),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach)}moveWidget(e,t,n){this.parent.isAttached&&B.sendMessage(n,pe.Msg.BeforeDetach),this.parent.node.removeChild(n.node),this.parent.isAttached&&B.sendMessage(n,pe.Msg.AfterDetach);let i=this.parent.node.children[t];this.parent.isAttached&&B.sendMessage(n,pe.Msg.BeforeAttach),this.parent.node.insertBefore(n.node,i),this.parent.isAttached&&B.sendMessage(n,pe.Msg.AfterAttach)}detachWidget(e,t){this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach)}}!function(e){e.clampDimension=function(e){return Math.max(0,Math.floor(e))}}(oe||(oe={}));var ve,_e,ye,be,we,De,xe,Ce,Ee,Se,Ae=oe;class ke extends ge{constructor(e){super(),this.widgetOffset=0,this._fixed=0,this._spacing=4,this._dirty=!1,this._hasNormedSizes=!1,this._sizers=[],this._items=[],this._handles=[],this._box=null,this._alignment="start",this._orientation="horizontal",this.renderer=e.renderer,void 0!==e.orientation&&(this._orientation=e.orientation),void 0!==e.alignment&&(this._alignment=e.alignment),void 0!==e.spacing&&(this._spacing=oe.clampDimension(e.spacing))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,this._sizers.length=0,this._handles.length=0,super.dispose()}get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,this.parent&&(this.parent.dataset.orientation=e,this.parent.fit()))}get alignment(){return this._alignment}set alignment(e){this._alignment!==e&&(this._alignment=e,this.parent&&(this.parent.dataset.alignment=e,this.parent.update()))}get spacing(){return this._spacing}set spacing(e){e=oe.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}get handles(){return this._handles}absoluteSizes(){return this._sizers.map((e=>e.size))}relativeSizes(){return ve.normalize(this._sizers.map((e=>e.size)))}setRelativeSizes(e,t=!0){let n=this._sizers.length,i=e.slice(0,n);for(;i.length0&&(e.sizeHint=e.size);ie.adjust(this._sizers,e,n),this.parent&&this.parent.update()}}init(){this.parent.dataset.orientation=this.orientation,this.parent.dataset.alignment=this.alignment,super.init()}attachWidget(e,t){let n=new me(t),i=ve.createHandle(this.renderer),s=ve.averageSize(this._sizers),r=ve.createSizer(s);D.insert(this._items,e,n),D.insert(this._sizers,e,r),D.insert(this._handles,e,i),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.node.appendChild(i),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){D.move(this._items,e,t),D.move(this._sizers,e,t),D.move(this._handles,e,t),this.parent.fit()}detachWidget(e,t){let n=D.removeAt(this._items,e),i=D.removeAt(this._handles,e);D.removeAt(this._sizers,e),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.node.removeChild(i),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}updateItemPosition(e,t,n,i,s,r,o){const a=this._items[e];if(a.isHidden)return;let l=this._handles[e].style;t?(n+=this.widgetOffset,a.update(n,i,o,s),n+=o,l.top=`${i}px`,l.left=`${n}px`,l.width=`${this._spacing}px`,l.height=`${s}px`):(i+=this.widgetOffset,a.update(n,i,r,o),i+=o,l.top=`${i}px`,l.left=`${n}px`,l.width=`${r}px`,l.height=`${this._spacing}px`)}_fit(){let e=0,t=-1;for(let n=0,i=this._items.length;n0&&(r.sizeHint=r.size),t.isHidden?(r.minSize=0,r.maxSize=0):(t.fit(),r.stretch=ke.getStretch(t.widget),n?(r.minSize=t.minWidth,r.maxSize=t.maxWidth,i+=t.minWidth,s=Math.max(s,t.minHeight)):(r.minSize=t.minHeight,r.maxSize=t.maxHeight,s+=t.minHeight,i=Math.max(i,t.minWidth)))}let r=this._box=M.boxSizing(this.parent.node);i+=r.horizontalSum,s+=r.verticalSum;let o=this.parent.node.style;o.minWidth=`${i}px`,o.minHeight=`${s}px`,this._dirty=!0,this.parent.parent&&B.sendMessage(this.parent.parent,pe.Msg.FitRequest),this._dirty&&B.sendMessage(this.parent,pe.Msg.UpdateRequest)}_update(e,t){this._dirty=!1;let n=0;for(let e=0,t=this._items.length;e0){let e;if(e=c?Math.max(0,r-this._fixed):Math.max(0,o-this._fixed),this._hasNormedSizes){for(let t of this._sizers)t.sizeHint*=e;this._hasNormedSizes=!1}let t=ie.calc(this._sizers,e);if(t>0)switch(this._alignment){case"start":break;case"center":a=0,l=t/2;break;case"end":a=0,l=t;break;case"justify":a=t/n,l=0;break;default:throw"unreachable"}}for(let e=0,t=this._items.length;e0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:function(e){e.parent&&e.parent.layout instanceof ke&&e.parent.fit()}}),e.createSizer=function(e){let t=new de;return t.sizeHint=Math.floor(e),t},e.createHandle=function(e){let t=e.createHandle();return t.style.position="absolute",t.style.contain="style",t},e.averageSize=function(e){return e.reduce(((e,t)=>e+t.size),0)/e.length||0},e.normalize=function(e){let t=e.length;if(0===t)return[];let n=e.reduce(((e,t)=>e+Math.abs(t)),0);return 0===n?e.map((e=>1/t)):e.map((e=>e/n))}}(ve||(ve={}));class Me extends ke{constructor(e){super({...e,orientation:e.orientation||"vertical"}),this._titles=[],this.titleSpace=e.titleSpace||22}get titleSpace(){return this.widgetOffset}set titleSpace(e){e=Ae.clampDimension(e),this.widgetOffset!==e&&(this.widgetOffset=e,this.parent&&this.parent.fit())}get titles(){return this._titles}dispose(){this.isDisposed||(this._titles.length=0,super.dispose())}updateTitle(e,t){const n=this._titles[e],i=n.classList.contains("lm-mod-expanded"),s=_e.createTitle(this.renderer,t.title,i);this._titles[e]=s,this.parent.node.replaceChild(s,n)}insertWidget(e,t){t.id||(t.id=`id-${N.UUID.uuid4()}`),super.insertWidget(e,t)}attachWidget(e,t){const n=_e.createTitle(this.renderer,t.title);D.insert(this._titles,e,n),this.parent.node.appendChild(n),t.node.setAttribute("role","region"),t.node.setAttribute("aria-labelledby",n.id),super.attachWidget(e,t)}moveWidget(e,t,n){D.move(this._titles,e,t),super.moveWidget(e,t,n)}detachWidget(e,t){const n=D.removeAt(this._titles,e);this.parent.node.removeChild(n),super.detachWidget(e,t)}updateItemPosition(e,t,n,i,s,r,o){const a=this._titles[e].style;a.top=`${i}px`,a.left=`${n}px`,a.height=`${this.widgetOffset}px`,a.width=t?`${s}px`:`${r}px`,super.updateItemPosition(e,t,n,i,s,r,o)}}!function(e){e.createTitle=function(e,t,n=!0){const i=e.createSectionTitle(t);return i.style.position="absolute",i.style.contain="strict",i.setAttribute("aria-label",`${t.label} Section`),i.setAttribute("aria-expanded",n?"true":"false"),i.setAttribute("aria-controls",t.owner.id),n&&i.classList.add("lm-mod-expanded"),i}}(_e||(_e={}));class Fe extends pe{constructor(e={}){super(),this.addClass("lm-Panel"),this.layout=ye.createLayout(e)}get widgets(){return this.layout.widgets}addWidget(e){this.layout.addWidget(e)}insertWidget(e,t){this.layout.insertWidget(e,t)}}!function(e){e.createLayout=function(e){return e.layout||new ge}}(ye||(ye={}));class Ie extends Fe{constructor(e={}){super({layout:be.createLayout(e)}),this._handleMoved=new H(this),this._pressData=null,this.addClass("lm-SplitPanel")}dispose(){this._releaseMouse(),super.dispose()}get orientation(){return this.layout.orientation}set orientation(e){this.layout.orientation=e}get alignment(){return this.layout.alignment}set alignment(e){this.layout.alignment=e}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}get renderer(){return this.layout.renderer}get handleMoved(){return this._handleMoved}get handles(){return this.layout.handles}relativeSizes(){return this.layout.relativeSizes()}setRelativeSizes(e,t=!0){this.layout.setRelativeSizes(e,t)}handleEvent(e){switch(e.type){case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("pointerdown",this)}onAfterDetach(e){this.node.removeEventListener("pointerdown",this),this._releaseMouse()}onChildAdded(e){e.child.addClass("lm-SplitPanel-child"),this._releaseMouse()}onChildRemoved(e){e.child.removeClass("lm-SplitPanel-child"),this._releaseMouse()}_evtKeyDown(e){this._pressData&&(e.preventDefault(),e.stopPropagation()),27===e.keyCode&&this._releaseMouse()}_evtPointerDown(e){if(0!==e.button)return;let t,n=this.layout,i=D.findFirstIndex(n.handles,(t=>t.contains(e.target)));if(-1===i)return;e.preventDefault(),e.stopPropagation(),document.addEventListener("pointerup",this,!0),document.addEventListener("pointermove",this,!0),document.addEventListener("keydown",this,!0),document.addEventListener("contextmenu",this,!0);let s=n.handles[i],r=s.getBoundingClientRect();t="horizontal"===n.orientation?e.clientX-r.left:e.clientY-r.top;let o=window.getComputedStyle(s),a=G.overrideCursor(o.cursor);this._pressData={index:i,delta:t,override:a}}_evtPointerMove(e){let t;e.preventDefault(),e.stopPropagation();let n=this.layout,i=this.node.getBoundingClientRect();t="horizontal"===n.orientation?e.clientX-i.left-this._pressData.delta:e.clientY-i.top-this._pressData.delta,n.moveHandle(this._pressData.index,t)}_evtPointerUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this._releaseMouse())}_releaseMouse(){this._pressData&&(this._pressData.override.dispose(),this._pressData=null,this._handleMoved.emit(),document.removeEventListener("keydown",this,!0),document.removeEventListener("pointerup",this,!0),document.removeEventListener("pointermove",this,!0),document.removeEventListener("contextmenu",this,!0))}}!function(e){class t{createHandle(){let e=document.createElement("div");return e.className="lm-SplitPanel-handle",e}}e.Renderer=t,e.defaultRenderer=new t,e.getStretch=function(e){return ke.getStretch(e)},e.setStretch=function(e,t){ke.setStretch(e,t)}}(Ie||(Ie={})),function(e){e.createLayout=function(e){return e.layout||new ke({renderer:e.renderer||Ie.defaultRenderer,orientation:e.orientation,alignment:e.alignment,spacing:e.spacing})}}(be||(be={}));class Oe extends Ie{constructor(e={}){super({...e,layout:we.createLayout(e)}),this._widgetSizesCache=new WeakMap,this._expansionToggled=new H(this),this.addClass("lm-AccordionPanel")}get renderer(){return this.layout.renderer}get titleSpace(){return this.layout.titleSpace}set titleSpace(e){this.layout.titleSpace=e}get titles(){return this.layout.titles}get expansionToggled(){return this._expansionToggled}addWidget(e){super.addWidget(e),e.title.changed.connect(this._onTitleChanged,this)}collapse(e){const t=this.layout.widgets[e];t&&!t.isHidden&&this._toggleExpansion(e)}expand(e){const t=this.layout.widgets[e];t&&t.isHidden&&this._toggleExpansion(e)}insertWidget(e,t){super.insertWidget(e,t),t.title.changed.connect(this._onTitleChanged,this)}handleEvent(e){switch(super.handleEvent(e),e.type){case"click":this._evtClick(e);break;case"keydown":this._eventKeyDown(e)}}onBeforeAttach(e){this.node.addEventListener("click",this),this.node.addEventListener("keydown",this),super.onBeforeAttach(e)}onAfterDetach(e){super.onAfterDetach(e),this.node.removeEventListener("click",this),this.node.removeEventListener("keydown",this)}_onTitleChanged(e){const t=D.findFirstIndex(this.widgets,(t=>t.contains(e.owner)));t>=0&&(this.layout.updateTitle(t,e.owner),this.update())}_computeWidgetSize(e){const t=this.layout,n=t.widgets[e];if(!n)return;const i=n.isHidden,s=t.absoluteSizes(),r=(i?-1:1)*this.spacing,o=s.reduce(((e,t)=>e+t));let a=[...s];if(i){const t=this._widgetSizesCache.get(n);if(!t)return;a[e]+=t;const i=a.map((e=>e-t>0)).lastIndexOf(!0);-1===i?a.forEach(((n,i)=>{i!==e&&(a[i]-=s[i]/o*(t-r))})):a[i]-=t-r}else{const t=s[e];this._widgetSizesCache.set(n,t),a[e]=0;const i=a.map((e=>e>0)).lastIndexOf(!0);if(-1===i)return;a[i]=s[i]+t+r}return a.map((e=>e/(o+r)))}_evtClick(e){const t=e.target;if(t){const n=D.findFirstIndex(this.titles,(e=>e.contains(t)));n>=0&&(e.preventDefault(),e.stopPropagation(),this._toggleExpansion(n))}}_eventKeyDown(e){if(e.defaultPrevented)return;const t=e.target;let n=!1;if(t){const i=D.findFirstIndex(this.titles,(e=>e.contains(t)));if(i>=0){const s=e.keyCode.toString();if(e.key.match(/Space|Enter/)||s.match(/13|32/))t.click(),n=!0;else if("horizontal"===this.orientation?e.key.match(/ArrowLeft|ArrowRight/)||s.match(/37|39/):e.key.match(/ArrowUp|ArrowDown/)||s.match(/38|40/)){const t=e.key.match(/ArrowLeft|ArrowUp/)||s.match(/37|38/)?-1:1,r=this.titles.length,o=(i+r+t)%r;this.titles[o].focus(),n=!0}else"End"===e.key||"35"===s?(this.titles[this.titles.length-1].focus(),n=!0):"Home"!==e.key&&"36"!==s||(this.titles[0].focus(),n=!0)}n&&e.preventDefault()}}_toggleExpansion(e){const t=this.titles[e],n=this.layout.widgets[e],i=this._computeWidgetSize(e);i&&this.setRelativeSizes(i,!1),n.isHidden?(t.classList.add("lm-mod-expanded"),t.setAttribute("aria-expanded","true"),n.show()):(t.classList.remove("lm-mod-expanded"),t.setAttribute("aria-expanded","false"),n.hide()),this._expansionToggled.emit(e)}}!function(e){class t extends Ie.Renderer{constructor(){super(),this.titleClassName="lm-AccordionPanel-title",this._titleID=0,this._titleKeys=new WeakMap,this._uuid=++t._nInstance}createCollapseIcon(e){return document.createElement("span")}createSectionTitle(e){const t=document.createElement("h3");t.setAttribute("tabindex","0"),t.id=this.createTitleKey(e),t.className=this.titleClassName;for(const n in e.dataset)t.dataset[n]=e.dataset[n];t.appendChild(this.createCollapseIcon(e)).className="lm-AccordionPanel-titleCollapser";const n=t.appendChild(document.createElement("span"));return n.className="lm-AccordionPanel-titleLabel",n.textContent=e.label,n.title=e.caption||e.label,t}createTitleKey(e){let t=this._titleKeys.get(e);return void 0===t&&(t=`title-key-${this._uuid}-${this._titleID++}`,this._titleKeys.set(e,t)),t}}t._nInstance=0,e.Renderer=t,e.defaultRenderer=new t}(Oe||(Oe={})),function(e){e.createLayout=function(e){return e.layout||new Me({renderer:e.renderer||Oe.defaultRenderer,orientation:e.orientation,alignment:e.alignment,spacing:e.spacing,titleSpace:e.titleSpace})}}(we||(we={}));class Pe extends ge{constructor(e={}){super(),this._fixed=0,this._spacing=4,this._dirty=!1,this._sizers=[],this._items=[],this._box=null,this._alignment="start",this._direction="top-to-bottom",void 0!==e.direction&&(this._direction=e.direction),void 0!==e.alignment&&(this._alignment=e.alignment),void 0!==e.spacing&&(this._spacing=Ae.clampDimension(e.spacing))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,this._sizers.length=0,super.dispose()}get direction(){return this._direction}set direction(e){this._direction!==e&&(this._direction=e,this.parent&&(this.parent.dataset.direction=e,this.parent.fit()))}get alignment(){return this._alignment}set alignment(e){this._alignment!==e&&(this._alignment=e,this.parent&&(this.parent.dataset.alignment=e,this.parent.update()))}get spacing(){return this._spacing}set spacing(e){e=Ae.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}init(){this.parent.dataset.direction=this.direction,this.parent.dataset.alignment=this.alignment,super.init()}attachWidget(e,t){D.insert(this._items,e,new me(t)),D.insert(this._sizers,e,new de),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){D.move(this._items,e,t),D.move(this._sizers,e,t),this.parent.update()}detachWidget(e,t){let n=D.removeAt(this._items,e);D.removeAt(this._sizers,e),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){let e=0;for(let t=0,n=this._items.length;t0)switch(this._alignment){case"start":break;case"center":l=0,c=i/2;break;case"end":l=0,c=i;break;case"justify":l=i/n,c=0;break;default:throw"unreachable"}for(let e=0,t=this._items.length;e0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:t}),e.sizeBasisProperty=new W({name:"sizeBasis",create:()=>0,coerce:(e,t)=>Math.max(0,Math.floor(t)),changed:t}),e.isHorizontal=function(e){return"left-to-right"===e||"right-to-left"===e},e.clampSpacing=function(e){return Math.max(0,Math.floor(e))}}(De||(De={}));class Be extends Fe{constructor(e={}){super({layout:xe.createLayout(e)}),this.addClass("lm-BoxPanel")}get direction(){return this.layout.direction}set direction(e){this.layout.direction=e}get alignment(){return this.layout.alignment}set alignment(e){this.layout.alignment=e}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}onChildAdded(e){e.child.addClass("lm-BoxPanel-child")}onChildRemoved(e){e.child.removeClass("lm-BoxPanel-child")}}!function(e){e.getStretch=function(e){return Pe.getStretch(e)},e.setStretch=function(e,t){Pe.setStretch(e,t)},e.getSizeBasis=function(e){return Pe.getSizeBasis(e)},e.setSizeBasis=function(e,t){Pe.setSizeBasis(e,t)}}(Be||(Be={})),function(e){e.createLayout=function(e){return e.layout||new Pe(e)}}(xe||(xe={}));class Re extends pe{constructor(e){super({node:Ce.createNode()}),this._activeIndex=-1,this._items=[],this._results=null,this.addClass("lm-CommandPalette"),this.setFlag(pe.Flag.DisallowLayout),this.commands=e.commands,this.renderer=e.renderer||Re.defaultRenderer,this.commands.commandChanged.connect(this._onGenericChange,this),this.commands.keyBindingChanged.connect(this._onGenericChange,this)}dispose(){this._items.length=0,this._results=null,super.dispose()}get searchNode(){return this.node.getElementsByClassName("lm-CommandPalette-search")[0]}get inputNode(){return this.node.getElementsByClassName("lm-CommandPalette-input")[0]}get contentNode(){return this.node.getElementsByClassName("lm-CommandPalette-content")[0]}get items(){return this._items}addItem(e){let t=Ce.createItem(this.commands,e);return this._items.push(t),this.refresh(),t}addItems(e){const t=e.map((e=>Ce.createItem(this.commands,e)));return t.forEach((e=>this._items.push(e))),this.refresh(),t}removeItem(e){this.removeItemAt(this._items.indexOf(e))}removeItemAt(e){D.removeAt(this._items,e)&&this.refresh()}clearItems(){0!==this._items.length&&(this._items.length=0,this.refresh())}refresh(){this._results=null,""!==this.inputNode.value?this.node.getElementsByClassName("lm-close-icon")[0].style.display="inherit":this.node.getElementsByClassName("lm-close-icon")[0].style.display="none",this.update()}handleEvent(e){switch(e.type){case"click":this._evtClick(e);break;case"keydown":this._evtKeyDown(e);break;case"input":this.refresh();break;case"focus":case"blur":this._toggleFocused()}}onBeforeAttach(e){this.node.addEventListener("click",this),this.node.addEventListener("keydown",this),this.node.addEventListener("input",this),this.node.addEventListener("focus",this,!0),this.node.addEventListener("blur",this,!0)}onAfterDetach(e){this.node.removeEventListener("click",this),this.node.removeEventListener("keydown",this),this.node.removeEventListener("input",this),this.node.removeEventListener("focus",this,!0),this.node.removeEventListener("blur",this,!0)}onAfterShow(e){this.update(),super.onAfterShow(e)}onActivateRequest(e){if(this.isAttached){let e=this.inputNode;e.focus(),e.select()}}onUpdateRequest(e){if(this.isHidden)return;let t=this.inputNode.value,n=this.contentNode,i=this._results;if(i||(i=this._results=Ce.search(this._items,t),this._activeIndex=t?D.findFirstIndex(i,Ce.canActivate):-1),!t&&0===i.length)return void te.render(null,n);if(t&&0===i.length){let e=this.renderer.renderEmptyMessage({query:t});return void te.render(e,n)}let s=this.renderer,r=this._activeIndex,o=new Array(i.length);for(let e=0,t=i.length;e=i.length)n.scrollTop=0;else{let e=n.children[r];M.scrollIntoViewIfNeeded(n,e)}}_evtClick(e){if(0!==e.button)return;if(e.target.classList.contains("lm-close-icon"))return this.inputNode.value="",void this.refresh();let t=D.findFirstIndex(this.contentNode.children,(t=>t.contains(e.target)));-1!==t&&(e.preventDefault(),e.stopPropagation(),this._execute(t))}_evtKeyDown(e){if(!(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey))switch(e.keyCode){case 13:e.preventDefault(),e.stopPropagation(),this._execute(this._activeIndex);break;case 38:e.preventDefault(),e.stopPropagation(),this._activatePreviousItem();break;case 40:e.preventDefault(),e.stopPropagation(),this._activateNextItem()}}_activateNextItem(){if(!this._results||0===this._results.length)return;let e=this._activeIndex,t=this._results.length,n=ee-t)),c=r.slice(0,l),u=r.slice(l);for(let e=0,t=u.length;en.command===e&&N.JSONExt.deepEqual(n.args,t)))||null}}}(Ce||(Ce={}));class Te extends pe{constructor(e){super({node:Ee.createNode()}),this._childIndex=-1,this._activeIndex=-1,this._openTimerID=0,this._closeTimerID=0,this._items=[],this._childMenu=null,this._parentMenu=null,this._aboutToClose=new H(this),this._menuRequested=new H(this),this.addClass("lm-Menu"),this.setFlag(pe.Flag.DisallowLayout),this.commands=e.commands,this.renderer=e.renderer||Te.defaultRenderer}dispose(){this.close(),this._items.length=0,super.dispose()}get aboutToClose(){return this._aboutToClose}get menuRequested(){return this._menuRequested}get parentMenu(){return this._parentMenu}get childMenu(){return this._childMenu}get rootMenu(){let e=this;for(;e._parentMenu;)e=e._parentMenu;return e}get leafMenu(){let e=this;for(;e._childMenu;)e=e._childMenu;return e}get contentNode(){return this.node.getElementsByClassName("lm-Menu-content")[0]}get activeItem(){return this._items[this._activeIndex]||null}set activeItem(e){this.activeIndex=e?this._items.indexOf(e):-1}get activeIndex(){return this._activeIndex}set activeIndex(e){(e<0||e>=this._items.length)&&(e=-1),-1===e||Ee.canActivate(this._items[e])||(e=-1),this._activeIndex!==e&&(this._activeIndex=e,this._activeIndex>=0&&this.contentNode.childNodes[this._activeIndex]&&this.contentNode.childNodes[this._activeIndex].focus(),this.update())}get items(){return this._items}activateNextItem(){let e=this._items.length,t=this._activeIndex,n=t{this.activeIndex=e}})}te.render(r,this.contentNode)}onCloseRequest(e){this._cancelOpenTimer(),this._cancelCloseTimer(),this.activeIndex=-1;let t=this._childMenu;t&&(this._childIndex=-1,this._childMenu=null,t._parentMenu=null,t.close());let n=this._parentMenu;n&&(this._parentMenu=null,n._childIndex=-1,n._childMenu=null,n.activate()),this.isAttached&&this._aboutToClose.emit(void 0),super.onCloseRequest(e)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation();let t=e.keyCode;if(13===t)return void this.triggerActiveItem();if(27===t)return void this.close();if(37===t)return void(this._parentMenu?this.close():this._menuRequested.emit("previous"));if(38===t)return void this.activatePreviousItem();if(39===t){let e=this.activeItem;return void(e&&"submenu"===e.type?this.triggerActiveItem():this.rootMenu._menuRequested.emit("next"))}if(40===t)return void this.activateNextItem();let n=Y().keyForKeydownEvent(e);if(!n)return;let i=this._activeIndex+1,s=Ee.findMnemonic(this._items,n,i);-1===s.index||s.multiple?-1!==s.index?this.activeIndex=s.index:-1!==s.auto&&(this.activeIndex=s.auto):(this.activeIndex=s.index,this.triggerActiveItem())}_evtMouseUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this.triggerActiveItem())}_evtMouseMove(e){let t=D.findFirstIndex(this.contentNode.children,(t=>M.hitTest(t,e.clientX,e.clientY)));if(t===this._activeIndex)return;if(this.activeIndex=t,t=this.activeIndex,t===this._childIndex)return this._cancelOpenTimer(),void this._cancelCloseTimer();-1!==this._childIndex&&this._startCloseTimer(),this._cancelOpenTimer();let n=this.activeItem;n&&"submenu"===n.type&&n.submenu&&this._startOpenTimer()}_evtMouseEnter(e){for(let e=this._parentMenu;e;e=e._parentMenu)e._cancelOpenTimer(),e._cancelCloseTimer(),e.activeIndex=e._childIndex}_evtMouseLeave(e){if(this._cancelOpenTimer(),!this._childMenu)return void(this.activeIndex=-1);let{clientX:t,clientY:n}=e;M.hitTest(this._childMenu.node,t,n)?this._cancelCloseTimer():(this.activeIndex=-1,this._startCloseTimer())}_evtMouseDown(e){this._parentMenu||(Ee.hitTestMenus(this,e.clientX,e.clientY)?(e.preventDefault(),e.stopPropagation()):this.close())}_openChildMenu(e=!1){let t=this.activeItem;if(!t||"submenu"!==t.type||!t.submenu)return void this._closeChildMenu();let n=t.submenu;if(n===this._childMenu)return;Te.saveWindowData(),this._closeChildMenu(),this._childMenu=n,this._childIndex=this._activeIndex,n._parentMenu=this,B.sendMessage(this,pe.Msg.UpdateRequest);let i=this.contentNode.children[this._activeIndex];Ee.openSubmenu(n,i),e&&(n.activeIndex=-1,n.activateNextItem()),n.activate()}_closeChildMenu(){this._childMenu&&this._childMenu.close()}_startOpenTimer(){0===this._openTimerID&&(this._openTimerID=window.setTimeout((()=>{this._openTimerID=0,this._openChildMenu()}),Ee.TIMER_DELAY))}_startCloseTimer(){0===this._closeTimerID&&(this._closeTimerID=window.setTimeout((()=>{this._closeTimerID=0,this._closeChildMenu()}),Ee.TIMER_DELAY))}_cancelOpenTimer(){0!==this._openTimerID&&(clearTimeout(this._openTimerID),this._openTimerID=0)}_cancelCloseTimer(){0!==this._closeTimerID&&(clearTimeout(this._closeTimerID),this._closeTimerID=0)}static saveWindowData(){Ee.saveWindowData()}}!function(e){class t{renderItem(e){let t=this.createItemClass(e),n=this.createItemDataset(e),i=this.createItemARIA(e);return ue.li({className:t,dataset:n,tabindex:"0",onfocus:e.onfocus,...i},this.renderIcon(e),this.renderLabel(e),this.renderShortcut(e),this.renderSubmenu(e))}renderIcon(e){let t=this.createIconClass(e);return ue.div({className:t},e.item.icon,e.item.iconLabel)}renderLabel(e){let t=this.formatLabel(e);return ue.div({className:"lm-Menu-itemLabel"},t)}renderShortcut(e){let t=this.formatShortcut(e);return ue.div({className:"lm-Menu-itemShortcut"},t)}renderSubmenu(e){return ue.div({className:"lm-Menu-itemSubmenuIcon"})}createItemClass(e){let t="lm-Menu-item";e.item.isEnabled||(t+=" lm-mod-disabled"),e.item.isToggled&&(t+=" lm-mod-toggled"),e.item.isVisible||(t+=" lm-mod-hidden"),e.active&&(t+=" lm-mod-active"),e.collapsed&&(t+=" lm-mod-collapsed");let n=e.item.className;return n&&(t+=` ${n}`),t}createItemDataset(e){let t,{type:n,command:i,dataset:s}=e.item;return t="command"===n?{...s,type:n,command:i}:{...s,type:n},t}createIconClass(e){let t="lm-Menu-itemIcon",n=e.item.iconClass;return n?`${t} ${n}`:t}createItemARIA(e){let t={};switch(e.item.type){case"separator":t.role="presentation";break;case"submenu":t["aria-haspopup"]="true",e.item.isEnabled||(t["aria-disabled"]="true");break;default:e.item.isEnabled||(t["aria-disabled"]="true"),t.role="menuitem"}return t}formatLabel(e){let{label:t,mnemonic:n}=e.item;if(n<0||n>=t.length)return t;let i=t.slice(0,n),s=t.slice(n+1),r=t[n];return[i,ue.span({className:"lm-Menu-itemMnemonic"},r),s]}formatShortcut(e){let t=e.item.keyBinding;return t?ae.formatKeystroke(t.keys):null}}e.Renderer=t,e.defaultRenderer=new t}(Te||(Te={})),function(e){e.TIMER_DELAY=300,e.SUBMENU_OVERLAP=3;let t=null,n=0;function i(){return n>0?(n--,t):r()}function s(e){return"separator"!==e.type&&e.isEnabled&&e.isVisible}function r(){return{pageXOffset:window.pageXOffset,pageYOffset:window.pageYOffset,clientWidth:document.documentElement.clientWidth,clientHeight:document.documentElement.clientHeight}}e.saveWindowData=function(){t=r(),n++},e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");return t.className="lm-Menu-content",e.appendChild(t),t.setAttribute("role","menu"),e.tabIndex=0,e},e.canActivate=s,e.createItem=function(e,t){return new o(e.commands,t)},e.hitTestMenus=function(e,t,n){for(let i=e;i;i=i.childMenu)if(M.hitTest(i.node,t,n))return!0;return!1},e.computeCollapsed=function(e){let t=new Array(e.length);D.fill(t,!1);let n=0,i=e.length;for(;n=0;--s){let n=e[s];if(n.isVisible){if("separator"!==n.type)break;t[s]=!0}}let r=!1;for(;++na+c&&(t=a+c-f),!r&&n+m>l+u&&(n>l+u?n=l+u-m:n-=m),p.transform=`translate(${Math.max(0,t)}px, ${Math.max(0,n)}px`,p.opacity="1"},e.openSubmenu=function(t,n){const s=i();let r=s.pageXOffset,o=s.pageYOffset,a=s.clientWidth,l=s.clientHeight;B.sendMessage(t,pe.Msg.UpdateRequest);let c=l,u=t.node,d=u.style;d.opacity="0",d.maxHeight=`${c}px`,pe.attach(t,document.body);let{width:h,height:p}=u.getBoundingClientRect(),f=M.boxSizing(t.node),m=n.getBoundingClientRect(),g=m.right-e.SUBMENU_OVERLAP;g+h>r+a&&(g=m.left+e.SUBMENU_OVERLAP-h);let v=m.top-f.borderTop-f.paddingTop;v+p>o+l&&(v=m.bottom+f.borderBottom+f.paddingBottom-p),d.transform=`translate(${Math.max(0,g)}px, ${Math.max(0,v)}px`,d.opacity="1"},e.findMnemonic=function(e,t,n){let i=-1,r=-1,o=!1,a=t.toUpperCase();for(let t=0,l=e.length;t=0&&hn.command===e&&N.JSONExt.deepEqual(n.args,t)))||null}return null}}}(Ee||(Ee={}));class Le{constructor(e){this._groupByTarget=!0,this._idTick=0,this._items=[],this._sortBySelector=!0;const{groupByTarget:t,sortBySelector:n,...i}=e;this.menu=new Te(i),this._groupByTarget=!1!==t,this._sortBySelector=!1!==n}addItem(e){let t=Se.createItem(e,this._idTick++);return this._items.push(t),new $((()=>{D.removeFirstOf(this._items,t)}))}open(e){if(Te.saveWindowData(),this.menu.clearItems(),0===this._items.length)return!1;let t=Se.matchItems(this._items,e,this._groupByTarget,this._sortBySelector);if(!t||0===t.length)return!1;for(const e of t)this.menu.addItem(e);return this.menu.open(e.clientX,e.clientY),!0}}!function(e){function t(e,t){let n=e.rank,i=t.rank;return n!==i?n=this._titles.length)&&(e=-1),this._currentIndex===e)return;let t=this._currentIndex,n=this._titles[t]||null,i=e,s=this._titles[i]||null;this._currentIndex=i,this._previousTitle=n,this.update(),this._currentChanged.emit({previousIndex:t,previousTitle:n,currentIndex:i,currentTitle:s})}get name(){return this._name}set name(e){this._name=e,e?this.contentNode.setAttribute("aria-label",e):this.contentNode.removeAttribute("aria-label")}get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._releaseMouse(),this._orientation=e,this.dataset.orientation=e,this.contentNode.setAttribute("aria-orientation",e))}get addButtonEnabled(){return this._addButtonEnabled}set addButtonEnabled(e){this._addButtonEnabled!==e&&(this._addButtonEnabled=e,e?this.addButtonNode.classList.remove("lm-mod-hidden"):this.addButtonNode.classList.add("lm-mod-hidden"))}get titles(){return this._titles}get contentNode(){return this.node.getElementsByClassName("lm-TabBar-content")[0]}get addButtonNode(){return this.node.getElementsByClassName("lm-TabBar-addButton")[0]}addTab(e){return this.insertTab(this._titles.length,e)}insertTab(e,t){this._releaseMouse();let n=ze.asTitle(t),i=this._titles.indexOf(n),s=Math.max(0,Math.min(e,this._titles.length));return-1===i?(D.insert(this._titles,s,n),n.changed.connect(this._onTitleChanged,this),this.update(),this._adjustCurrentForInsert(s,n),n):(s===this._titles.length&&s--,i===s||(D.move(this._titles,i,s),this.update(),this._adjustCurrentForMove(i,s)),n)}removeTab(e){this.removeTabAt(this._titles.indexOf(e))}removeTabAt(e){this._releaseMouse();let t=D.removeAt(this._titles,e);t&&(t.changed.disconnect(this._onTitleChanged,this),t===this._previousTitle&&(this._previousTitle=null),this.update(),this._adjustCurrentForRemove(e,t))}clearTabs(){if(0===this._titles.length)return;this._releaseMouse();for(let e of this._titles)e.changed.disconnect(this._onTitleChanged,this);let e=this.currentIndex,t=this.currentTitle;this._currentIndex=-1,this._previousTitle=null,this._titles.length=0,this.update(),-1!==e&&this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null})}releaseMouse(){this._releaseMouse()}handleEvent(e){switch(e.type){case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"dblclick":this._evtDblClick(e);break;case"keydown":e.eventPhase===Event.CAPTURING_PHASE?this._evtKeyDownCapturing(e):this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("pointerdown",this),this.node.addEventListener("dblclick",this),this.node.addEventListener("keydown",this)}onAfterDetach(e){this.node.removeEventListener("pointerdown",this),this.node.removeEventListener("dblclick",this),this.node.removeEventListener("keydown",this),this._releaseMouse()}onUpdateRequest(e){var t;let n=this._titles,i=this.renderer,s=this.currentTitle,r=new Array(n.length);const o=null!==(t=this._getCurrentTabindex())&&void 0!==t?t:this._currentIndex>-1?this._currentIndex:0;for(let e=0,t=n.length;eM.hitTest(t,e.clientX,e.clientY)));if(-1===n)return;let i=this.titles[n],s=t[n].querySelector(".lm-TabBar-tabLabel");if(s&&s.contains(e.target)){let e=i.label||"",t=s.innerHTML;s.innerHTML="";let n=document.createElement("input");n.classList.add("lm-TabBar-tabInput"),n.value=e,s.appendChild(n);let r=()=>{n.removeEventListener("blur",r),s.innerHTML=t,this.node.addEventListener("keydown",this)};n.addEventListener("dblclick",(e=>e.stopPropagation())),n.addEventListener("blur",r),n.addEventListener("keydown",(e=>{"Enter"===e.key?(""!==n.value&&(i.label=i.caption=n.value),r()):"Escape"===e.key&&r()})),this.node.removeEventListener("keydown",this),n.select(),n.focus(),s.children.length>0&&s.children[0].focus()}}_evtKeyDownCapturing(e){e.eventPhase===Event.CAPTURING_PHASE&&(e.preventDefault(),e.stopPropagation(),"Escape"===e.key&&this._releaseMouse())}_evtKeyDown(e){var t,n,i;if("Tab"!==e.key&&e.eventPhase!==Event.CAPTURING_PHASE)if("Enter"===e.key||"Spacebar"===e.key||" "===e.key){const t=document.activeElement;if(this.addButtonEnabled&&this.addButtonNode.contains(t))e.preventDefault(),e.stopPropagation(),this._addRequested.emit();else{const n=D.findFirstIndex(this.contentNode.children,(e=>e.contains(t)));n>=0&&(e.preventDefault(),e.stopPropagation(),this.currentIndex=n)}}else if(je.includes(e.key)){const s=[...this.contentNode.children];if(this.addButtonEnabled&&s.push(this.addButtonNode),s.length<=1)return;e.preventDefault(),e.stopPropagation();let r,o=s.indexOf(document.activeElement);-1===o&&(o=this._currentIndex),"ArrowRight"===e.key&&"horizontal"===this._orientation||"ArrowDown"===e.key&&"vertical"===this._orientation?r=null!==(t=s[o+1])&&void 0!==t?t:s[0]:"ArrowLeft"===e.key&&"horizontal"===this._orientation||"ArrowUp"===e.key&&"vertical"===this._orientation?r=null!==(n=s[o-1])&&void 0!==n?n:s[s.length-1]:"Home"===e.key?r=s[0]:"End"===e.key&&(r=s[s.length-1]),r&&(null===(i=s[o])||void 0===i||i.setAttribute("tabindex","-1"),null==r||r.setAttribute("tabindex","0"),r.focus())}}_evtPointerDown(e){if(0!==e.button&&1!==e.button)return;if(this._dragData)return;if(e.target.classList.contains("lm-TabBar-tabInput"))return;let t=this.addButtonEnabled&&this.addButtonNode.contains(e.target),n=this.contentNode.children,i=D.findFirstIndex(n,(t=>M.hitTest(t,e.clientX,e.clientY)));if(-1===i&&!t)return;if(e.preventDefault(),e.stopPropagation(),this._dragData={tab:n[i],index:i,pressX:e.clientX,pressY:e.clientY,tabPos:-1,tabSize:-1,tabPressPos:-1,targetIndex:-1,tabLayout:null,contentRect:null,override:null,dragActive:!1,dragAborted:!1,detachRequested:!1},this.document.addEventListener("pointerup",this,!0),1===e.button||t)return;let s=n[i].querySelector(this.renderer.closeIconSelector);s&&s.contains(e.target)||(this.tabsMovable&&(this.document.addEventListener("pointermove",this,!0),this.document.addEventListener("keydown",this,!0),this.document.addEventListener("contextmenu",this,!0)),this.allowDeselect&&this.currentIndex===i?this.currentIndex=-1:this.currentIndex=i,-1!==this.currentIndex&&this._tabActivateRequested.emit({index:this.currentIndex,title:this.currentTitle}))}_evtPointerMove(e){let t=this._dragData;if(!t)return;e.preventDefault(),e.stopPropagation();let n=this.contentNode.children;if(t.dragActive||ze.dragExceeded(t,e)){if(!t.dragActive){let e=t.tab.getBoundingClientRect();"horizontal"===this._orientation?(t.tabPos=t.tab.offsetLeft,t.tabSize=e.width,t.tabPressPos=t.pressX-e.left):(t.tabPos=t.tab.offsetTop,t.tabSize=e.height,t.tabPressPos=t.pressY-e.top),t.tabPressOffset={x:t.pressX-e.left,y:t.pressY-e.top},t.tabLayout=ze.snapTabLayout(n,this._orientation),t.contentRect=this.contentNode.getBoundingClientRect(),t.override=G.overrideCursor("default"),t.tab.classList.add("lm-mod-dragging"),this.addClass("lm-mod-dragging"),t.dragActive=!0}if(!t.detachRequested&&ze.detachExceeded(t,e)){t.detachRequested=!0;let i=t.index,s=e.clientX,r=e.clientY,o=n[i],a=this._titles[i];if(this._tabDetachRequested.emit({index:i,title:a,tab:o,clientX:s,clientY:r,offset:t.tabPressOffset}),t.dragAborted)return}ze.layoutTabs(n,t,e,this._orientation)}}_evtPointerUp(e){if(0!==e.button&&1!==e.button)return;const t=this._dragData;if(!t)return;if(e.preventDefault(),e.stopPropagation(),this.document.removeEventListener("pointermove",this,!0),this.document.removeEventListener("pointerup",this,!0),this.document.removeEventListener("keydown",this,!0),this.document.removeEventListener("contextmenu",this,!0),!t.dragActive){if(this._dragData=null,this.addButtonEnabled&&this.addButtonNode.contains(e.target))return void this._addRequested.emit(void 0);let n=this.contentNode.children,i=D.findFirstIndex(n,(t=>M.hitTest(t,e.clientX,e.clientY)));if(i!==t.index)return;let s=this._titles[i];if(!s.closable)return;if(1===e.button)return void this._tabCloseRequested.emit({index:i,title:s});let r=n[i].querySelector(this.renderer.closeIconSelector);return r&&r.contains(e.target)?void this._tabCloseRequested.emit({index:i,title:s}):void 0}if(0!==e.button)return;ze.finalizeTabPosition(t,this._orientation),t.tab.classList.remove("lm-mod-dragging");let n=ze.parseTransitionDuration(t.tab);setTimeout((()=>{if(t.dragAborted)return;this._dragData=null,ze.resetTabPositions(this.contentNode.children,this._orientation),t.override.dispose(),this.removeClass("lm-mod-dragging");let e=t.index,n=t.targetIndex;-1!==n&&e!==n&&(D.move(this._titles,e,n),this._adjustCurrentForMove(e,n),this._tabMoved.emit({fromIndex:e,toIndex:n,title:this._titles[n]}),B.sendMessage(this,pe.Msg.UpdateRequest))}),n)}_releaseMouse(){let e=this._dragData;e&&(this._dragData=null,this.document.removeEventListener("pointermove",this,!0),this.document.removeEventListener("pointerup",this,!0),this.document.removeEventListener("keydown",this,!0),this.document.removeEventListener("contextmenu",this,!0),e.dragAborted=!0,e.dragActive&&(ze.resetTabPositions(this.contentNode.children,this._orientation),e.override.dispose(),e.tab.classList.remove("lm-mod-dragging"),this.removeClass("lm-mod-dragging")))}_adjustCurrentForInsert(e,t){let n=this.currentTitle,i=this._currentIndex,s=this.insertBehavior;if("select-tab"===s||"select-tab-if-needed"===s&&-1===i)return this._currentIndex=e,this._previousTitle=n,void this._currentChanged.emit({previousIndex:i,previousTitle:n,currentIndex:e,currentTitle:t});i>=e&&this._currentIndex++}_adjustCurrentForMove(e,t){this._currentIndex===e?this._currentIndex=t:this._currentIndex=t?this._currentIndex++:this._currentIndex>e&&this._currentIndex<=t&&this._currentIndex--}_adjustCurrentForRemove(e,t){let n=this._currentIndex,i=this.removeBehavior;if(n===e){if(0===this._titles.length)return this._currentIndex=-1,void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null});if("select-tab-after"===i)return this._currentIndex=Math.min(e,this._titles.length-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});if("select-tab-before"===i)return this._currentIndex=Math.max(0,e-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});if("select-previous-tab"===i)return this._previousTitle?(this._currentIndex=this._titles.indexOf(this._previousTitle),this._previousTitle=null):this._currentIndex=Math.min(e,this._titles.length-1),void this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:this._currentIndex,currentTitle:this.currentTitle});this._currentIndex=-1,this._currentChanged.emit({previousIndex:e,previousTitle:t,currentIndex:-1,currentTitle:null})}else n>e&&this._currentIndex--}_onTitleChanged(e){this.update()}}var ze,Ue,qe,We,He,Ke,$e,Ve,Je,Ge,Ye,Xe;!function(e){class t{constructor(){this.closeIconSelector=".lm-TabBar-tabCloseIcon",this._tabID=0,this._tabKeys=new WeakMap,this._uuid=++t._nInstance}renderTab(e){let t=e.title.caption,n=this.createTabKey(e),i=n,s=this.createTabStyle(e),r=this.createTabClass(e),o=this.createTabDataset(e),a=this.createTabARIA(e);return e.title.closable?ue.li({id:i,key:n,className:r,title:t,style:s,dataset:o,...a},this.renderIcon(e),this.renderLabel(e),this.renderCloseIcon(e)):ue.li({id:i,key:n,className:r,title:t,style:s,dataset:o,...a},this.renderIcon(e),this.renderLabel(e))}renderIcon(e){const{title:t}=e;let n=this.createIconClass(e);return ue.div({className:n},t.icon,t.iconLabel)}renderLabel(e){return ue.div({className:"lm-TabBar-tabLabel"},e.title.label)}renderCloseIcon(e){return ue.div({className:"lm-TabBar-tabCloseIcon"})}createTabKey(e){let t=this._tabKeys.get(e.title);return void 0===t&&(t=`tab-key-${this._uuid}-${this._tabID++}`,this._tabKeys.set(e.title,t)),t}createTabStyle(e){return{zIndex:`${e.zIndex}`}}createTabClass(e){let t="lm-TabBar-tab";return e.title.className&&(t+=` ${e.title.className}`),e.title.closable&&(t+=" lm-mod-closable"),e.current&&(t+=" lm-mod-current"),t}createTabDataset(e){return e.title.dataset}createTabARIA(e){var t;return{role:"tab","aria-selected":e.current.toString(),tabindex:`${null!==(t=e.tabIndex)&&void 0!==t?t:"-1"}`}}createIconClass(e){let t="lm-TabBar-tabIcon",n=e.title.iconClass;return n?`${t} ${n}`:t}}t._nInstance=0,e.Renderer=t,e.defaultRenderer=new t,e.addButtonSelector=".lm-TabBar-addButton"}(Ne||(Ne={})),function(e){e.DRAG_THRESHOLD=5,e.DETACH_THRESHOLD=20,e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");t.setAttribute("role","tablist"),t.className="lm-TabBar-content",e.appendChild(t);let n=document.createElement("div");return n.className="lm-TabBar-addButton lm-mod-hidden",n.setAttribute("tabindex","-1"),n.setAttribute("role","button"),e.appendChild(n),e},e.asTitle=function(e){return e instanceof he?e:new he(e)},e.parseTransitionDuration=function(e){let t=window.getComputedStyle(e);return 1e3*(parseFloat(t.transitionDuration)||0)},e.snapTabLayout=function(e,t){let n=new Array(e.length);for(let i=0,s=e.length;i=e.DRAG_THRESHOLD||s>=e.DRAG_THRESHOLD},e.detachExceeded=function(t,n){let i=t.contentRect;return n.clientX=i.right+e.DETACH_THRESHOLD||n.clientY=i.bottom+e.DETACH_THRESHOLD},e.layoutTabs=function(e,t,n,i){let s,r,o,a;"horizontal"===i?(s=t.pressX,r=n.clientX-t.contentRect.left,o=n.clientX,a=t.contentRect.width):(s=t.pressY,r=n.clientY-t.contentRect.top,o=n.clientY,a=t.contentRect.height);let l=t.index,c=r-t.tabPressPos,u=c+t.tabSize;for(let n=0,r=e.length;n>1);if(nt.index&&u>h)r=-t.tabSize-d.margin+"px",l=Math.max(l,n);else if(n===t.index){let e=o-s,n=a-(t.tabPos+t.tabSize);r=`${Math.max(-t.tabPos,Math.min(e,n))}px`}else r="";"horizontal"===i?e[n].style.left=r:e[n].style.top=r}t.targetIndex=l},e.finalizeTabPosition=function(e,t){let n,i;if(n="horizontal"===t?e.contentRect.width:e.contentRect.height,e.targetIndex===e.index)i=0;else if(e.targetIndex>e.index){let t=e.tabLayout[e.targetIndex];i=t.pos+t.size-e.tabSize-e.tabPos}else i=e.tabLayout[e.targetIndex].pos-e.tabPos;let s=n-(e.tabPos+e.tabSize),r=Math.max(-e.tabPos,Math.min(i,s));"horizontal"===t?e.tab.style.left=`${r}px`:e.tab.style.top=`${r}px`},e.resetTabPositions=function(e,t){for(const n of e)"horizontal"===t?n.style.left="":n.style.top=""}}(ze||(ze={}));class Ze extends fe{constructor(e){super(),this._spacing=4,this._dirty=!1,this._root=null,this._box=null,this._items=new Map,this.renderer=e.renderer,void 0!==e.spacing&&(this._spacing=Ae.clampDimension(e.spacing)),this._document=e.document||document,this._hiddenMode=void 0!==e.hiddenMode?e.hiddenMode:pe.HiddenMode.Display}dispose(){let e=this[Symbol.iterator]();this._items.forEach((e=>{e.dispose()})),this._box=null,this._root=null,this._items.clear();for(const t of e)t.dispose();super.dispose()}get hiddenMode(){return this._hiddenMode}set hiddenMode(e){if(this._hiddenMode!==e){this._hiddenMode=e;for(const e of this.tabBars())if(e.titles.length>1)for(const t of e.titles)t.owner.hiddenMode=this._hiddenMode}}get spacing(){return this._spacing}set spacing(e){e=Ae.clampDimension(e),this._spacing!==e&&(this._spacing=e,this.parent&&this.parent.fit())}get isEmpty(){return null===this._root}[Symbol.iterator](){return this._root?this._root.iterAllWidgets():S()}widgets(){return this._root?this._root.iterUserWidgets():S()}selectedWidgets(){return this._root?this._root.iterSelectedWidgets():S()}tabBars(){return this._root?this._root.iterTabBars():S()}handles(){return this._root?this._root.iterHandles():S()}moveHandle(e,t,n){let i=e.classList.contains("lm-mod-hidden");if(!this._root||i)return;let s,r=this._root.findSplitNode(e);r&&(s="horizontal"===r.node.orientation?t-e.offsetLeft:n-e.offsetTop,0!==s&&(r.node.holdSizes(),ie.adjust(r.node.sizers,r.index,s),this.parent&&this.parent.update()))}saveLayout(){return this._root?(this._root.holdAllSizes(),{main:this._root.createConfig()}):{main:null}}restoreLayout(e){let t,n=new Set;t=e.main?Ue.normalizeAreaConfig(e.main,n):null;let i=this.widgets(),s=this.tabBars(),r=this.handles();this._root=null;for(const e of i)n.has(e)||(e.parent=null);for(const e of s)e.dispose();for(const e of r)e.parentNode&&e.parentNode.removeChild(e);for(const e of n)e.parent=this.parent;this._root=t?Ue.realizeAreaConfig(t,{createTabBar:e=>this._createTabBar(),createHandle:()=>this._createHandle()},this._document):null,this.parent&&(n.forEach((e=>{this.attachWidget(e)})),this.parent.fit())}addWidget(e,t={}){let n=t.ref||null,i=t.mode||"tab-after",s=null;if(this._root&&n&&(s=this._root.findTabNode(n)),n&&!s)throw new Error("Reference widget is not in the layout.");switch(e.parent=this.parent,i){case"tab-after":this._insertTab(e,n,s,!0);break;case"tab-before":this._insertTab(e,n,s,!1);break;case"split-top":this._insertSplit(e,n,s,"vertical",!1);break;case"split-left":this._insertSplit(e,n,s,"horizontal",!1);break;case"split-right":this._insertSplit(e,n,s,"horizontal",!0);break;case"split-bottom":this._insertSplit(e,n,s,"vertical",!0);break;case"merge-top":this._insertSplit(e,n,s,"vertical",!1,!0);break;case"merge-left":this._insertSplit(e,n,s,"horizontal",!1,!0);break;case"merge-right":this._insertSplit(e,n,s,"horizontal",!0,!0);break;case"merge-bottom":this._insertSplit(e,n,s,"vertical",!0,!0)}this.parent&&(this.attachWidget(e),this.parent.fit())}removeWidget(e){this._removeWidget(e),this.parent&&(this.detachWidget(e),this.parent.fit())}hitTestTabAreas(e,t){if(!this._root||!this.parent||!this.parent.isVisible)return null;this._box||(this._box=M.boxSizing(this.parent.node));let n=this.parent.node.getBoundingClientRect(),i=e-n.left-this._box.borderLeft,s=t-n.top-this._box.borderTop,r=this._root.hitTestTabNodes(i,s);if(!r)return null;let{tabBar:o,top:a,left:l,width:c,height:u}=r,d=this._box.borderLeft+this._box.borderRight,h=this._box.borderTop+this._box.borderBottom;return{tabBar:o,x:i,y:s,top:a,left:l,right:n.width-d-(l+c),bottom:n.height-h-(a+u),width:c,height:u}}init(){super.init();for(const e of this)this.attachWidget(e);for(const e of this.handles())this.parent.node.appendChild(e);this.parent.fit()}attachWidget(e){this.parent.node!==e.node.parentNode&&(this._items.set(e,new me(e)),this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeAttach),this.parent.node.appendChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterAttach))}detachWidget(e){if(this.parent.node!==e.node.parentNode)return;this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeDetach),this.parent.node.removeChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterDetach);let t=this._items.get(e);t&&(this._items.delete(e),t.dispose())}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_removeWidget(e){if(!this._root)return;let t=this._root.findTabNode(e);if(!t)return;if(Ue.removeAria(e),t.tabBar.titles.length>1)return t.tabBar.removeTab(e.title),void(this._hiddenMode===pe.HiddenMode.Scale&&1==t.tabBar.titles.length&&(t.tabBar.titles[0].owner.hiddenMode=pe.HiddenMode.Display));if(t.tabBar.dispose(),this._root===t)return void(this._root=null);this._root.holdAllSizes();let n=t.parent;t.parent=null;let i=D.removeFirstOf(n.children,t),s=D.removeAt(n.handles,i);if(D.removeAt(n.sizers,i),s.parentNode&&s.parentNode.removeChild(s),n.children.length>1)return void n.syncHandles();let r=n.parent;n.parent=null;let o=n.children[0],a=n.handles[0];if(n.children.length=0,n.handles.length=0,n.sizers.length=0,a.parentNode&&a.parentNode.removeChild(a),this._root===n)return o.parent=null,void(this._root=o);let l=r,c=l.children.indexOf(n);if(o instanceof Ue.TabLayoutNode)return o.parent=l,void(l.children[c]=o);let u=D.removeAt(l.handles,c);D.removeAt(l.children,c),D.removeAt(l.sizers,c),u.parentNode&&u.parentNode.removeChild(u);for(let e=0,t=o.children.length;e=n.length)&&(i=0),{type:"tab-area",widgets:n,currentIndex:i}}(t,n):function(t,n){let i=t.orientation,s=[],r=[];for(let o=0,a=t.children.length;o{let l=s(i,n,r),c=t(e.sizes[a]),u=n.createHandle();o.children.push(l),o.handles.push(u),o.sizers.push(c),l.parent=o})),o.syncHandles(),o.normalizeSizes(),o}(r,o,a),l};class n{constructor(e){this.parent=null,this._top=0,this._left=0,this._width=0,this._height=0;let t=new de,n=new de;t.stretch=0,n.stretch=1,this.tabBar=e,this.sizers=[t,n]}get top(){return this._top}get left(){return this._left}get width(){return this._width}get height(){return this._height}*iterAllWidgets(){yield this.tabBar,yield*this.iterUserWidgets()}*iterUserWidgets(){for(const e of this.tabBar.titles)yield e.owner}*iterSelectedWidgets(){let e=this.tabBar.currentTitle;e&&(yield e.owner)}*iterTabBars(){yield this.tabBar}*iterHandles(){}findTabNode(e){return-1!==this.tabBar.titles.indexOf(e.title)?this:null}findSplitNode(e){return null}findFirstTabNode(){return this}hitTestTabNodes(e,t){return e=this._left+this._width||t=this._top+this._height?null:this}createConfig(){return{type:"tab-area",widgets:this.tabBar.titles.map((e=>e.owner)),currentIndex:this.tabBar.currentIndex}}holdAllSizes(){}fit(e,t){let n=0,i=0,s=t.get(this.tabBar),r=this.tabBar.currentTitle,o=r?t.get(r.owner):void 0,[a,l]=this.sizers;return s&&s.fit(),o&&o.fit(),s&&!s.isHidden?(n=Math.max(n,s.minWidth),i+=s.minHeight,a.minSize=s.minHeight,a.maxSize=s.maxHeight):(a.minSize=0,a.maxSize=0),o&&!o.isHidden?(n=Math.max(n,o.minWidth),i+=o.minHeight,l.minSize=o.minHeight,l.maxSize=1/0):(l.minSize=0,l.maxSize=1/0),{minWidth:n,minHeight:i,maxWidth:1/0,maxHeight:1/0}}update(e,t,n,i,s,r){this._top=t,this._left=e,this._width=n,this._height=i;let o=r.get(this.tabBar),a=this.tabBar.currentTitle,l=a?r.get(a.owner):void 0;if(ie.calc(this.sizers,i),o&&!o.isHidden){let i=this.sizers[0].size;o.update(e,t,n,i),t+=i}if(l&&!l.isHidden){let i=this.sizers[1].size;l.update(e,t,n,i)}}}e.TabLayoutNode=n;class i{constructor(e){this.parent=null,this.normalized=!1,this.children=[],this.sizers=[],this.handles=[],this.orientation=e}*iterAllWidgets(){for(const e of this.children)yield*e.iterAllWidgets()}*iterUserWidgets(){for(const e of this.children)yield*e.iterUserWidgets()}*iterSelectedWidgets(){for(const e of this.children)yield*e.iterSelectedWidgets()}*iterTabBars(){for(const e of this.children)yield*e.iterTabBars()}*iterHandles(){yield*this.handles;for(const e of this.children)yield*e.iterHandles()}findTabNode(e){for(let t=0,n=this.children.length;te.createConfig())),sizes:t}}syncHandles(){this.handles.forEach(((e,t)=>{e.setAttribute("data-orientation",this.orientation),t===this.handles.length-1?e.classList.add("lm-mod-hidden"):e.classList.remove("lm-mod-hidden")}))}holdSizes(){for(const e of this.sizers)e.sizeHint=e.size}holdAllSizes(){for(const e of this.children)e.holdAllSizes();this.holdSizes()}normalizeSizes(){let e=this.sizers.length;if(0===e)return;this.holdSizes();let t=this.sizers.reduce(((e,t)=>e+t.sizeHint),0);if(0===t)for(const t of this.sizers)t.size=t.sizeHint=1/e;else for(const e of this.sizers)e.size=e.sizeHint/=t;this.normalized=!0}createNormalizedSizes(){let e=this.sizers.length;if(0===e)return[];let t=this.sizers.map((e=>e.size)),n=t.reduce(((e,t)=>e+t),0);if(0===n)for(let n=t.length-1;n>-1;n--)t[n]=1/e;else for(let e=t.length-1;e>-1;e--)t[e]/=n;return t}fit(e,t){let n="horizontal"===this.orientation,i=Math.max(0,this.children.length-1)*e,s=n?i:0,r=n?0:i;for(let i=0,o=this.children.length;ithis._createTabBar(),createHandle:()=>this._createHandle()};this.layout=new Ze({document:this._document,renderer:t,spacing:e.spacing,hiddenMode:e.hiddenMode}),this.overlay=e.overlay||new Qe.Overlay,this.node.appendChild(this.overlay.node)}dispose(){this._releaseMouse(),this.overlay.hide(0),this._drag&&this._drag.dispose(),super.dispose()}get hiddenMode(){return this.layout.hiddenMode}set hiddenMode(e){this.layout.hiddenMode=e}get layoutModified(){return this._layoutModified}get addRequested(){return this._addRequested}get renderer(){return this.layout.renderer}get spacing(){return this.layout.spacing}set spacing(e){this.layout.spacing=e}get mode(){return this._mode}set mode(e){if(this._mode===e)return;this._mode=e,this.dataset.mode=e;let t=this.layout;switch(e){case"multiple-document":for(const e of t.tabBars())e.show();break;case"single-document":t.restoreLayout(qe.createSingleDocumentConfig(this));break;default:throw"unreachable"}B.postMessage(this,qe.LayoutModified)}get tabsMovable(){return this._tabsMovable}set tabsMovable(e){this._tabsMovable=e;for(const t of this.tabBars())t.tabsMovable=e}get tabsConstrained(){return this._tabsConstrained}set tabsConstrained(e){this._tabsConstrained=e}get addButtonEnabled(){return this._addButtonEnabled}set addButtonEnabled(e){this._addButtonEnabled=e;for(const t of this.tabBars())t.addButtonEnabled=e}get isEmpty(){return this.layout.isEmpty}*widgets(){yield*this.layout.widgets()}*selectedWidgets(){yield*this.layout.selectedWidgets()}*tabBars(){yield*this.layout.tabBars()}*handles(){yield*this.layout.handles()}selectWidget(e){let t=A(this.tabBars(),(t=>-1!==t.titles.indexOf(e.title)));if(!t)throw new Error("Widget is not contained in the dock panel.");t.currentTitle=e.title}activateWidget(e){this.selectWidget(e),e.activate()}saveLayout(){return this.layout.saveLayout()}restoreLayout(e){this._mode="multiple-document",this.layout.restoreLayout(e),(F.IS_EDGE||F.IS_IE)&&B.flush(),B.postMessage(this,qe.LayoutModified)}addWidget(e,t={}){"single-document"===this._mode?this.layout.addWidget(e):this.layout.addWidget(e,t),B.postMessage(this,qe.LayoutModified)}processMessage(e){"layout-modified"===e.type?this._layoutModified.emit(void 0):super.processMessage(e)}handleEvent(e){switch(e.type){case"lm-dragenter":this._evtDragEnter(e);break;case"lm-dragleave":this._evtDragLeave(e);break;case"lm-dragover":this._evtDragOver(e);break;case"lm-drop":this._evtDrop(e);break;case"pointerdown":this._evtPointerDown(e);break;case"pointermove":this._evtPointerMove(e);break;case"pointerup":this._evtPointerUp(e);break;case"keydown":this._evtKeyDown(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("lm-dragenter",this),this.node.addEventListener("lm-dragleave",this),this.node.addEventListener("lm-dragover",this),this.node.addEventListener("lm-drop",this),this.node.addEventListener("pointerdown",this)}onAfterDetach(e){this.node.removeEventListener("lm-dragenter",this),this.node.removeEventListener("lm-dragleave",this),this.node.removeEventListener("lm-dragover",this),this.node.removeEventListener("lm-drop",this),this.node.removeEventListener("pointerdown",this),this._releaseMouse()}onChildAdded(e){qe.isGeneratedTabBarProperty.get(e.child)||e.child.addClass("lm-DockPanel-widget")}onChildRemoved(e){qe.isGeneratedTabBarProperty.get(e.child)||(e.child.removeClass("lm-DockPanel-widget"),B.postMessage(this,qe.LayoutModified))}_evtDragEnter(e){e.mimeData.hasData("application/vnd.lumino.widget-factory")&&(e.preventDefault(),e.stopPropagation())}_evtDragLeave(e){e.preventDefault(),this._tabsConstrained&&e.source!==this||(e.stopPropagation(),this.overlay.hide(1))}_evtDragOver(e){e.preventDefault(),this._tabsConstrained&&e.source!==this||"invalid"===this._showOverlay(e.clientX,e.clientY)?e.dropAction="none":(e.stopPropagation(),e.dropAction=e.proposedAction)}_evtDrop(e){if(e.preventDefault(),this.overlay.hide(0),"none"===e.proposedAction)return void(e.dropAction="none");let{clientX:t,clientY:n}=e,{zone:i,target:s}=qe.findDropTarget(this,t,n,this._edges);if(this._tabsConstrained&&e.source!==this||"invalid"===i)return void(e.dropAction="none");let r=e.mimeData.getData("application/vnd.lumino.widget-factory");if("function"!=typeof r)return void(e.dropAction="none");let o=r();if(!(o instanceof pe))return void(e.dropAction="none");if(o.contains(this))return void(e.dropAction="none");let a=s?qe.getDropRef(s.tabBar):null;switch(i){case"root-all":this.addWidget(o);break;case"root-top":this.addWidget(o,{mode:"split-top"});break;case"root-left":this.addWidget(o,{mode:"split-left"});break;case"root-right":this.addWidget(o,{mode:"split-right"});break;case"root-bottom":this.addWidget(o,{mode:"split-bottom"});break;case"widget-all":case"widget-tab":this.addWidget(o,{mode:"tab-after",ref:a});break;case"widget-top":this.addWidget(o,{mode:"split-top",ref:a});break;case"widget-left":this.addWidget(o,{mode:"split-left",ref:a});break;case"widget-right":this.addWidget(o,{mode:"split-right",ref:a});break;case"widget-bottom":this.addWidget(o,{mode:"split-bottom",ref:a});break;default:throw"unreachable"}e.dropAction=e.proposedAction,e.stopPropagation(),this.activateWidget(o)}_evtKeyDown(e){e.preventDefault(),e.stopPropagation(),27===e.keyCode&&(this._releaseMouse(),B.postMessage(this,qe.LayoutModified))}_evtPointerDown(e){if(0!==e.button)return;let t=this.layout,n=e.target,i=A(t.handles(),(e=>e.contains(n)));if(!i)return;e.preventDefault(),e.stopPropagation(),this._document.addEventListener("keydown",this,!0),this._document.addEventListener("pointerup",this,!0),this._document.addEventListener("pointermove",this,!0),this._document.addEventListener("contextmenu",this,!0);let s=i.getBoundingClientRect(),r=e.clientX-s.left,o=e.clientY-s.top,a=window.getComputedStyle(i),l=G.overrideCursor(a.cursor,this._document);this._pressData={handle:i,deltaX:r,deltaY:o,override:l}}_evtPointerMove(e){if(!this._pressData)return;e.preventDefault(),e.stopPropagation();let t=this.node.getBoundingClientRect(),n=e.clientX-t.left-this._pressData.deltaX,i=e.clientY-t.top-this._pressData.deltaY;this.layout.moveHandle(this._pressData.handle,n,i)}_evtPointerUp(e){0===e.button&&(e.preventDefault(),e.stopPropagation(),this._releaseMouse(),B.postMessage(this,qe.LayoutModified))}_releaseMouse(){this._pressData&&(this._pressData.override.dispose(),this._pressData=null,this._document.removeEventListener("keydown",this,!0),this._document.removeEventListener("pointerup",this,!0),this._document.removeEventListener("pointermove",this,!0),this._document.removeEventListener("contextmenu",this,!0))}_showOverlay(e,t){let n,i,s,r,{zone:o,target:a}=qe.findDropTarget(this,e,t,this._edges);if("invalid"===o)return this.overlay.hide(100),o;let l=M.boxSizing(this.node),c=this.node.getBoundingClientRect();switch(o){case"root-all":n=l.paddingTop,i=l.paddingLeft,s=l.paddingRight,r=l.paddingBottom;break;case"root-top":n=l.paddingTop,i=l.paddingLeft,s=l.paddingRight,r=c.height*qe.GOLDEN_RATIO;break;case"root-left":n=l.paddingTop,i=l.paddingLeft,s=c.width*qe.GOLDEN_RATIO,r=l.paddingBottom;break;case"root-right":n=l.paddingTop,i=c.width*qe.GOLDEN_RATIO,s=l.paddingRight,r=l.paddingBottom;break;case"root-bottom":n=c.height*qe.GOLDEN_RATIO,i=l.paddingLeft,s=l.paddingRight,r=l.paddingBottom;break;case"widget-all":n=a.top,i=a.left,s=a.right,r=a.bottom;break;case"widget-top":n=a.top,i=a.left,s=a.right,r=a.bottom+a.height/2;break;case"widget-left":n=a.top,i=a.left,s=a.right+a.width/2,r=a.bottom;break;case"widget-right":n=a.top,i=a.left+a.width/2,s=a.right,r=a.bottom;break;case"widget-bottom":n=a.top+a.height/2,i=a.left,s=a.right,r=a.bottom;break;case"widget-tab":{const e=a.tabBar.node.getBoundingClientRect().height;n=a.top,i=a.left,s=a.right,r=a.bottom+a.height-e;break}default:throw"unreachable"}return this.overlay.show({top:n,left:i,right:s,bottom:r}),o}_createTabBar(){let e=this._renderer.createTabBar(this._document);return qe.isGeneratedTabBarProperty.set(e,!0),"single-document"===this._mode&&e.hide(),e.tabsMovable=this._tabsMovable,e.allowDeselect=!1,e.addButtonEnabled=this._addButtonEnabled,e.removeBehavior="select-previous-tab",e.insertBehavior="select-tab-if-needed",e.tabMoved.connect(this._onTabMoved,this),e.currentChanged.connect(this._onCurrentChanged,this),e.tabCloseRequested.connect(this._onTabCloseRequested,this),e.tabDetachRequested.connect(this._onTabDetachRequested,this),e.tabActivateRequested.connect(this._onTabActivateRequested,this),e.addRequested.connect(this._onTabAddRequested,this),e}_createHandle(){return this._renderer.createHandle()}_onTabMoved(){B.postMessage(this,qe.LayoutModified)}_onCurrentChanged(e,t){let{previousTitle:n,currentTitle:i}=t;n&&n.owner.hide(),i&&i.owner.show(),(F.IS_EDGE||F.IS_IE)&&B.flush(),B.postMessage(this,qe.LayoutModified)}_onTabAddRequested(e){this._addRequested.emit(e)}_onTabActivateRequested(e,t){t.title.owner.activate()}_onTabCloseRequested(e,t){t.title.owner.close()}_onTabDetachRequested(e,t){if(this._drag)return;e.releaseMouse();let{title:n,tab:i,clientX:s,clientY:r,offset:o}=t,a=new N.MimeData;a.setData("application/vnd.lumino.widget-factory",(()=>n.owner));let l=i.cloneNode(!0);o&&(l.style.top=`-${o.y}px`,l.style.left=`-${o.x}px`),this._drag=new G({document:this._document,mimeData:a,dragImage:l,proposedAction:"move",supportedActions:"move",source:this}),i.classList.add("lm-mod-hidden"),this._drag.start(s,r).then((()=>{this._drag=null,i.classList.remove("lm-mod-hidden")}))}}!function(e){e.Overlay=class{constructor(){this._timer=-1,this._hidden=!0,this.node=document.createElement("div"),this.node.classList.add("lm-DockPanel-overlay"),this.node.classList.add("lm-mod-hidden"),this.node.style.position="absolute",this.node.style.contain="strict"}show(e){let t=this.node.style;t.top=`${e.top}px`,t.left=`${e.left}px`,t.right=`${e.right}px`,t.bottom=`${e.bottom}px`,clearTimeout(this._timer),this._timer=-1,this._hidden&&(this._hidden=!1,this.node.classList.remove("lm-mod-hidden"))}hide(e){if(!this._hidden)return e<=0?(clearTimeout(this._timer),this._timer=-1,this._hidden=!0,void this.node.classList.add("lm-mod-hidden")):void(-1===this._timer&&(this._timer=window.setTimeout((()=>{this._timer=-1,this._hidden=!0,this.node.classList.add("lm-mod-hidden")}),e)))}};class t{createTabBar(e){let t=new Ne({document:e});return t.addClass("lm-DockPanel-tabBar"),t}createHandle(){let e=document.createElement("div");return e.className="lm-DockPanel-handle",e}}e.Renderer=t,e.defaultRenderer=new t}(Qe||(Qe={})),function(e){e.GOLDEN_RATIO=.618,e.DEFAULT_EDGES={top:12,right:40,bottom:40,left:40},e.LayoutModified=new q("layout-modified"),e.isGeneratedTabBarProperty=new W({name:"isGeneratedTabBar",create:()=>!1}),e.createSingleDocumentConfig=function(e){if(e.isEmpty)return{main:null};let t=Array.from(e.widgets()),n=e.selectedWidgets().next().value,i=n?t.indexOf(n):-1;return{main:{type:"tab-area",widgets:t,currentIndex:i}}},e.findDropTarget=function(e,t,n,i){if(!M.hitTest(e.node,t,n))return{zone:"invalid",target:null};let s=e.layout;if(s.isEmpty)return{zone:"root-all",target:null};if("multiple-document"===e.mode){let s=e.node.getBoundingClientRect(),r=t-s.left+1,o=n-s.top+1,a=s.right-t,l=s.bottom-n;switch(Math.min(o,a,l,r)){case o:if(od&&l>d&&a>h&&c>h)return{zone:"widget-all",target:r};switch(o/=d,a/=h,l/=d,c/=h,Math.min(o,a,l,c)){case o:u="widget-left";break;case a:u="widget-top";break;case l:u="widget-right";break;case c:u="widget-bottom";break;default:throw"unreachable"}return{zone:u,target:r}},e.getDropRef=function(e){return 0===e.titles.length?null:e.currentTitle?e.currentTitle.owner:e.titles[e.titles.length-1].owner}}(qe||(qe={}));class et extends fe{constructor(e={}){super(e),this._dirty=!1,this._rowSpacing=4,this._columnSpacing=4,this._items=[],this._rowStarts=[],this._columnStarts=[],this._rowSizers=[new de],this._columnSizers=[new de],this._box=null,void 0!==e.rowCount&&We.reallocSizers(this._rowSizers,e.rowCount),void 0!==e.columnCount&&We.reallocSizers(this._columnSizers,e.columnCount),void 0!==e.rowSpacing&&(this._rowSpacing=We.clampValue(e.rowSpacing)),void 0!==e.columnSpacing&&(this._columnSpacing=We.clampValue(e.columnSpacing))}dispose(){for(const e of this._items){let t=e.widget;e.dispose(),t.dispose()}this._box=null,this._items.length=0,this._rowStarts.length=0,this._rowSizers.length=0,this._columnStarts.length=0,this._columnSizers.length=0,super.dispose()}get rowCount(){return this._rowSizers.length}set rowCount(e){e!==this.rowCount&&(We.reallocSizers(this._rowSizers,e),this.parent&&this.parent.fit())}get columnCount(){return this._columnSizers.length}set columnCount(e){e!==this.columnCount&&(We.reallocSizers(this._columnSizers,e),this.parent&&this.parent.fit())}get rowSpacing(){return this._rowSpacing}set rowSpacing(e){e=We.clampValue(e),this._rowSpacing!==e&&(this._rowSpacing=e,this.parent&&this.parent.fit())}get columnSpacing(){return this._columnSpacing}set columnSpacing(e){e=We.clampValue(e),this._columnSpacing!==e&&(this._columnSpacing=e,this.parent&&this.parent.fit())}rowStretch(e){let t=this._rowSizers[e];return t?t.stretch:-1}setRowStretch(e,t){let n=this._rowSizers[e];n&&(t=We.clampValue(t),n.stretch!==t&&(n.stretch=t,this.parent&&this.parent.update()))}columnStretch(e){let t=this._columnSizers[e];return t?t.stretch:-1}setColumnStretch(e,t){let n=this._columnSizers[e];n&&(t=We.clampValue(t),n.stretch!==t&&(n.stretch=t,this.parent&&this.parent.update()))}*[Symbol.iterator](){for(const e of this._items)yield e.widget}addWidget(e){-1===D.findFirstIndex(this._items,(t=>t.widget===e))&&(this._items.push(new me(e)),this.parent&&this.attachWidget(e))}removeWidget(e){let t=D.findFirstIndex(this._items,(t=>t.widget===e));if(-1===t)return;let n=D.removeAt(this._items,t);this.parent&&this.detachWidget(e),n.dispose()}init(){super.init();for(const e of this)this.attachWidget(e)}attachWidget(e){this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeAttach),this.parent.node.appendChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterAttach),this.parent.fit()}detachWidget(e){this.parent.isAttached&&B.sendMessage(e,pe.Msg.BeforeDetach),this.parent.node.removeChild(e.node),this.parent.isAttached&&B.sendMessage(e,pe.Msg.AfterDetach),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){for(let e=0,t=this.rowCount;e!e.isHidden));for(let t=0,n=e.length;t({row:0,column:0,rowSpan:1,columnSpan:1}),changed:function(e){e.parent&&e.parent.layout instanceof et&&e.parent.fit()}}),e.normalizeConfig=function(e){return{row:Math.max(0,Math.floor(e.row||0)),column:Math.max(0,Math.floor(e.column||0)),rowSpan:Math.max(1,Math.floor(e.rowSpan||0)),columnSpan:Math.max(1,Math.floor(e.columnSpan||0))}},e.clampValue=function(e){return Math.max(0,Math.floor(e))},e.rowSpanCmp=function(t,n){let i=e.cellConfigProperty.get(t.widget),s=e.cellConfigProperty.get(n.widget);return i.rowSpan-s.rowSpan},e.columnSpanCmp=function(t,n){let i=e.cellConfigProperty.get(t.widget),s=e.cellConfigProperty.get(n.widget);return i.columnSpan-s.columnSpan},e.reallocSizers=function(e,t){for(t=Math.max(1,Math.floor(t));e.lengtht&&(e.length=t)},e.distributeMin=function(e,t,n,i){if(n=i)return;let r=(i-s)/(n-t+1);for(let i=t;i<=n;++i)e[i].minSize+=r}}(We||(We={}));class tt extends pe{constructor(e={}){super({node:He.createNode()}),this._activeIndex=-1,this._tabFocusIndex=0,this._menus=[],this._childMenu=null,this._overflowMenu=null,this._menuItemSizes=[],this._overflowIndex=-1,this.addClass("lm-MenuBar"),this.setFlag(pe.Flag.DisallowLayout),this.renderer=e.renderer||tt.defaultRenderer,this._forceItemsPosition=e.forceItemsPosition||{forceX:!0,forceY:!0},this._overflowMenuOptions=e.overflowMenuOptions||{isVisible:!0}}dispose(){this._closeChildMenu(),this._menus.length=0,super.dispose()}get childMenu(){return this._childMenu}get overflowIndex(){return this._overflowIndex}get overflowMenu(){return this._overflowMenu}get contentNode(){return this.node.getElementsByClassName("lm-MenuBar-content")[0]}get activeMenu(){return this._menus[this._activeIndex]||null}set activeMenu(e){this.activeIndex=e?this._menus.indexOf(e):-1}get activeIndex(){return this._activeIndex}set activeIndex(e){(e<0||e>=this._menus.length)&&(e=-1),e>-1&&0===this._menus[e].items.length&&(e=-1),this._activeIndex!==e&&(this._activeIndex=e,this.update())}get menus(){return this._menus}openActiveMenu(){-1!==this._activeIndex&&(this._openChildMenu(),this._childMenu&&(this._childMenu.activeIndex=-1,this._childMenu.activateNextItem()))}addMenu(e,t=!0){this.insertMenu(this._menus.length,e,t)}insertMenu(e,t,n=!0){this._closeChildMenu();let i=this._menus.indexOf(t),s=Math.max(0,Math.min(e,this._menus.length));if(-1===i)return D.insert(this._menus,s,t),t.addClass("lm-MenuBar-menu"),t.aboutToClose.connect(this._onMenuAboutToClose,this),t.menuRequested.connect(this._onMenuMenuRequested,this),t.title.changed.connect(this._onTitleChanged,this),void(n&&this.update());s===this._menus.length&&s--,i!==s&&(D.move(this._menus,i,s),n&&this.update())}removeMenu(e,t=!0){this.removeMenuAt(this._menus.indexOf(e),t)}removeMenuAt(e,t=!0){this._closeChildMenu();let n=D.removeAt(this._menus,e);n&&(n.aboutToClose.disconnect(this._onMenuAboutToClose,this),n.menuRequested.disconnect(this._onMenuMenuRequested,this),n.title.changed.disconnect(this._onTitleChanged,this),n.removeClass("lm-MenuBar-menu"),t&&this.update())}clearMenus(){if(0!==this._menus.length){this._closeChildMenu();for(let e of this._menus)e.aboutToClose.disconnect(this._onMenuAboutToClose,this),e.menuRequested.disconnect(this._onMenuMenuRequested,this),e.title.changed.disconnect(this._onTitleChanged,this),e.removeClass("lm-MenuBar-menu");this._menus.length=0,this.update()}}handleEvent(e){switch(e.type){case"keydown":this._evtKeyDown(e);break;case"mousedown":this._evtMouseDown(e);break;case"mousemove":this._evtMouseMove(e);break;case"focusout":this._evtFocusOut(e);break;case"contextmenu":e.preventDefault(),e.stopPropagation()}}onBeforeAttach(e){this.node.addEventListener("keydown",this),this.node.addEventListener("mousedown",this),this.node.addEventListener("mousemove",this),this.node.addEventListener("focusout",this),this.node.addEventListener("contextmenu",this)}onAfterDetach(e){this.node.removeEventListener("keydown",this),this.node.removeEventListener("mousedown",this),this.node.removeEventListener("mousemove",this),this.node.removeEventListener("focusout",this),this.node.removeEventListener("contextmenu",this),this._closeChildMenu()}onActivateRequest(e){this.isAttached&&this._focusItemAt(0)}onResize(e){this.update(),super.onResize(e)}onUpdateRequest(e){var t;let n=this._menus,i=this.renderer,s=this._activeIndex,r=this._tabFocusIndex>=0&&this._tabFocusIndex-1?this._overflowIndex:n.length,a=0,l=!1;o=null!==this._overflowMenu?o-1:o;let c=new Array(o);for(let e=0;e{this._tabFocusIndex=e,this.activeIndex=e}}),a+=this._menuItemSizes[e],n[e].title.label===this._overflowMenuOptions.title&&(l=!0,o--);if(this._overflowMenuOptions.isVisible)if(this._overflowIndex>-1&&!l){if(null===this._overflowMenu){const e=null!==(t=this._overflowMenuOptions.title)&&void 0!==t?t:"...";this._overflowMenu=new Te({commands:new ae}),this._overflowMenu.title.label=e,this._overflowMenu.title.mnemonic=0,this.addMenu(this._overflowMenu,!1)}for(let e=n.length-2;e>=o;e--){const t=this.menus[e];t.title.mnemonic=0,this._overflowMenu.insertItem(0,{type:"submenu",submenu:t}),this.removeMenu(t,!1)}c[o]=i.renderItem({title:this._overflowMenu.title,active:o===s&&0!==n[o].items.length,tabbable:o===r,disabled:0===n[o].items.length,onfocus:()=>{this._tabFocusIndex=o,this.activeIndex=o}}),o++}else if(null!==this._overflowMenu){let e=this._overflowMenu.items,t=this.node.offsetWidth,s=this._overflowMenu.items.length;for(let l=0;lthis._menuItemSizes[s]){let t=e[0].submenu;this._overflowMenu.removeItemAt(0),this.insertMenu(o,t,!1),c[o]=i.renderItem({title:t.title,active:!1,tabbable:o===r,disabled:0===n[o].items.length,onfocus:()=>{this._tabFocusIndex=o,this.activeIndex=o}}),o++}}0===this._overflowMenu.items.length&&(this.removeMenu(this._overflowMenu,!1),c.pop(),this._overflowMenu=null,this._overflowIndex=-1)}te.render(c,this.contentNode),this._updateOverflowIndex()}_updateOverflowIndex(){if(!this._overflowMenuOptions.isVisible)return;const e=this.contentNode.childNodes;let t=this.node.offsetWidth,n=0,i=-1,s=e.length;if(0==this._menuItemSizes.length)for(let r=0;rt&&-1===i&&(i=r)}else for(let e=0;et){i=e;break}this._overflowIndex=i}_evtKeyDown(e){let t=e.keyCode;if(9===t)return void(this.activeIndex=-1);if(e.preventDefault(),e.stopPropagation(),13===t||32===t||38===t||40===t){if(this.activeIndex=this._tabFocusIndex,this.activeIndex!==this._tabFocusIndex)return;return void this.openActiveMenu()}if(27===t)return this._closeChildMenu(),void this._focusItemAt(this.activeIndex);if(37===t||39===t){let e=37===t?-1:1,n=this._tabFocusIndex+e,i=this._menus.length;for(let t=0;tM.hitTest(t,e.clientX,e.clientY)));if(-1!==t){if(0===e.button)if(this._childMenu)this._closeChildMenu(),this.activeIndex=t;else{e.preventDefault();const n=this._positionForMenu(t);Te.saveWindowData(),this.activeIndex=t,this._openChildMenu(n)}}else this._closeChildMenu()}_evtMouseMove(e){let t=D.findFirstIndex(this.contentNode.children,(t=>M.hitTest(t,e.clientX,e.clientY)));if(t===this._activeIndex)return;if(-1===t&&this._childMenu)return;const n=t>=0&&this._childMenu?this._positionForMenu(t):null;Te.saveWindowData(),this.activeIndex=t,n&&this._openChildMenu(n)}_positionForMenu(e){let t=this.contentNode.children[e],{left:n,bottom:i}=t.getBoundingClientRect();return{top:i,left:n}}_evtFocusOut(e){this._childMenu||this.node.contains(e.relatedTarget)||(this.activeIndex=-1)}_focusItemAt(e){const t=this.contentNode.childNodes[e];t&&t.focus()}_openChildMenu(e={}){let t=this.activeMenu;if(!t)return void this._closeChildMenu();let n=this._childMenu;if(n===t)return;this._childMenu=t,n?n.close():document.addEventListener("mousedown",this,!0),this._tabFocusIndex=this.activeIndex,B.sendMessage(this,pe.Msg.UpdateRequest);let{left:i,top:s}=e;void 0!==i&&void 0!==s||({left:i,top:s}=this._positionForMenu(this._activeIndex)),n||this.addClass("lm-mod-active"),t.items.length>0&&t.open(i,s,this._forceItemsPosition)}_closeChildMenu(){if(!this._childMenu)return;this.removeClass("lm-mod-active"),document.removeEventListener("mousedown",this,!0);let e=this._childMenu;this._childMenu=null,e.close(),this.activeIndex=-1}_onMenuAboutToClose(e){e===this._childMenu&&(this.removeClass("lm-mod-active"),document.removeEventListener("mousedown",this,!0),this._childMenu=null,this.activeIndex=-1)}_onMenuMenuRequested(e,t){if(e!==this._childMenu)return;let n=this._activeIndex,i=this._menus.length;switch(t){case"next":this.activeIndex=n===i-1?0:n+1;break;case"previous":this.activeIndex=0===n?i-1:n-1}this.openActiveMenu()}_onTitleChanged(){this.update()}}!function(e){class t{renderItem(e){let t=this.createItemClass(e),n=this.createItemDataset(e),i=this.createItemARIA(e);return ue.li({className:t,dataset:n,...e.disabled?{}:{tabindex:e.tabbable?"0":"-1"},onfocus:e.onfocus,...i},this.renderIcon(e),this.renderLabel(e))}renderIcon(e){let t=this.createIconClass(e);return ue.div({className:t},e.title.icon,e.title.iconLabel)}renderLabel(e){let t=this.formatLabel(e);return ue.div({className:"lm-MenuBar-itemLabel"},t)}createItemClass(e){let t="lm-MenuBar-item";return e.title.className&&(t+=` ${e.title.className}`),e.active&&!e.disabled&&(t+=" lm-mod-active"),t}createItemDataset(e){return e.title.dataset}createItemARIA(e){return{role:"menuitem","aria-haspopup":"true","aria-disabled":e.disabled?"true":"false"}}createIconClass(e){let t="lm-MenuBar-itemIcon",n=e.title.iconClass;return n?`${t} ${n}`:t}formatLabel(e){let{label:t,mnemonic:n}=e.title;if(n<0||n>=t.length)return t;let i=t.slice(0,n),s=t.slice(n+1),r=t[n];return[i,ue.span({className:"lm-MenuBar-itemMnemonic"},r),s]}}e.Renderer=t,e.defaultRenderer=new t}(tt||(tt={})),function(e){e.createNode=function(){let e=document.createElement("div"),t=document.createElement("ul");return t.className="lm-MenuBar-content",e.appendChild(t),t.setAttribute("role","menubar"),e},e.findMnemonic=function(e,t,n){let i=-1,s=-1,r=!1,o=t.toUpperCase();for(let t=0,a=e.length;t=0&&u1&&this.widgets.forEach((e=>{e.hiddenMode=this._hiddenMode})))}dispose(){for(const e of this._items)e.dispose();this._box=null,this._items.length=0,super.dispose()}attachWidget(e,t){this._hiddenMode===pe.HiddenMode.Scale&&this._items.length>0?(1===this._items.length&&(this.widgets[0].hiddenMode=pe.HiddenMode.Scale),t.hiddenMode=pe.HiddenMode.Scale):t.hiddenMode=pe.HiddenMode.Display,D.insert(this._items,e,new me(t)),this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeAttach),this.parent.node.appendChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterAttach),this.parent.fit()}moveWidget(e,t,n){D.move(this._items,e,t),this.parent.update()}detachWidget(e,t){let n=D.removeAt(this._items,e);this.parent.isAttached&&B.sendMessage(t,pe.Msg.BeforeDetach),this.parent.node.removeChild(t.node),this.parent.isAttached&&B.sendMessage(t,pe.Msg.AfterDetach),n.widget.node.style.zIndex="",this._hiddenMode===pe.HiddenMode.Scale&&(t.hiddenMode=pe.HiddenMode.Display,1===this._items.length&&(this._items[0].widget.hiddenMode=pe.HiddenMode.Display)),n.dispose(),this.parent.fit()}onBeforeShow(e){super.onBeforeShow(e),this.parent.update()}onBeforeAttach(e){super.onBeforeAttach(e),this.parent.fit()}onChildShown(e){this.parent.fit()}onChildHidden(e){this.parent.fit()}onResize(e){this.parent.isVisible&&this._update(e.width,e.height)}onUpdateRequest(e){this.parent.isVisible&&this._update(-1,-1)}onFitRequest(e){this.parent.isAttached&&this._fit()}_fit(){let e=0,t=0;for(let n=0,i=this._items.length;n=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(Je||(Je={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(Ye||(Ye={}));class st{constructor(e){this._delegate=new h.PromiseDelegate,this._plugins=new Map,this._services=new Map,this._started=!1,this._bubblingKeydown=!1,this.commands=new E,this.contextMenu=new Le({commands:this.commands,renderer:e.contextMenuRenderer}),this.shell=e.shell}get started(){return this._delegate.promise}getPluginDescription(e){var t,n;return null!==(n=null===(t=this._plugins.get(e))||void 0===t?void 0:t.description)&&void 0!==n?n:""}hasPlugin(e){return this._plugins.has(e)}isPluginActivated(e){var t,n;return null!==(n=null===(t=this._plugins.get(e))||void 0===t?void 0:t.activated)&&void 0!==n&&n}listPlugins(){return Array.from(this._plugins.keys())}registerPlugin(e){if(this._plugins.has(e.id))throw new TypeError(`Plugin '${e.id}' is already registered.`);const t=Xe.createPluginData(e);Xe.ensureNoCycle(t,this._plugins,this._services),t.provides&&this._services.set(t.provides,t.id),this._plugins.set(t.id,t)}registerPlugins(e){for(const t of e)this.registerPlugin(t)}deregisterPlugin(e,t){const n=this._plugins.get(e);if(n){if(n.activated&&!t)throw new Error(`Plugin '${e}' is still active.`);this._plugins.delete(e)}}async activatePlugin(e){const t=this._plugins.get(e);if(!t)throw new ReferenceError(`Plugin '${e}' is not registered.`);if(t.activated)return;if(t.promise)return t.promise;const n=t.requires.map((e=>this.resolveRequiredService(e))),i=t.optional.map((e=>this.resolveOptionalService(e)));return t.promise=Promise.all([...n,...i]).then((e=>t.activate.apply(void 0,[this,...e]))).then((e=>{t.service=e,t.activated=!0,t.promise=null})).catch((e=>{throw t.promise=null,e})),t.promise}async deactivatePlugin(e){const t=this._plugins.get(e);if(!t)throw new ReferenceError(`Plugin '${e}' is not registered.`);if(!t.activated)return[];if(!t.deactivate)throw new TypeError(`Plugin '${e}'#deactivate() method missing`);const n=Xe.findDependents(e,this._plugins,this._services),i=n.map((e=>this._plugins.get(e)));for(const t of i)if(!t.deactivate)throw new TypeError(`Plugin ${t.id}#deactivate() method missing (depends on ${e})`);for(const e of i){const t=[...e.requires,...e.optional].map((e=>{const t=this._services.get(e);return t?this._plugins.get(t).service:null}));await e.deactivate(this,...t),e.service=null,e.activated=!1}return n.pop(),n}async resolveRequiredService(e){const t=this._services.get(e);if(!t)throw new TypeError(`No provider for: ${e.name}.`);const n=this._plugins.get(t);return n.activated||await this.activatePlugin(t),n.service}async resolveOptionalService(e){const t=this._services.get(e);if(!t)return null;const n=this._plugins.get(t);if(!n.activated)try{await this.activatePlugin(t)}catch(e){return console.error(e),null}return n.service}start(e={}){if(this._started)return this._delegate.promise;this._started=!0,this._bubblingKeydown=e.bubblingKeydown||!1;const t=e.hostID||"",n=Xe.collectStartupPlugins(this._plugins,e).map((e=>this.activatePlugin(e).catch((t=>{console.error(`Plugin '${e}' failed to activate.`),console.error(t)}))));return Promise.all(n).then((()=>{this.attachShell(t),this.addEventListeners(),this._delegate.resolve()})),this._delegate.promise}get deferredPlugins(){return Array.from(this._plugins).filter((([e,t])=>"defer"===t.autoStart)).map((([e,t])=>e))}async activateDeferredPlugins(){const e=this.deferredPlugins.filter((e=>this._plugins.get(e).autoStart)).map((e=>this.activatePlugin(e)));await Promise.all(e)}handleEvent(e){switch(e.type){case"resize":this.evtResize(e);break;case"keydown":this.evtKeydown(e);break;case"contextmenu":this.evtContextMenu(e)}}attachShell(e){pe.attach(this.shell,e&&document.getElementById(e)||document.body)}addEventListeners(){document.addEventListener("contextmenu",this),document.addEventListener("keydown",this,!this._bubblingKeydown),window.addEventListener("resize",this)}evtKeydown(e){this.commands.processKeydownEvent(e)}evtContextMenu(e){e.shiftKey||this.contextMenu.open(e)&&(e.preventDefault(),e.stopPropagation())}evtResize(e){this.shell.update()}}!function(e){e.createPluginData=function(e){var t,n,i,s;return{id:e.id,description:null!==(t=e.description)&&void 0!==t?t:"",service:null,promise:null,activated:!1,activate:e.activate,deactivate:null!==(n=e.deactivate)&&void 0!==n?n:null,provides:null!==(i=e.provides)&&void 0!==i?i:null,autoStart:null!==(s=e.autoStart)&&void 0!==s&&s,requires:e.requires?e.requires.slice():[],optional:e.optional?e.optional.slice():[]}},e.ensureNoCycle=function(e,t,n){const i=[...e.requires,...e.optional],s=i=>{if(i===e.provides)return!0;const o=n.get(i);if(!o)return!1;const a=t.get(o),l=[...a.requires,...a.optional];return 0!==l.length&&(r.push(o),!!l.some(s)||(r.pop(),!1))};if(!e.provides||0===i.length)return;const r=[e.id];if(i.some(s))throw new ReferenceError(`Cycle detected: ${r.join(" -> ")}.`)},e.findDependents=function(e,t,n){const i=new Array,s=e=>{const s=t.get(e),r=[...s.requires,...s.optional];i.push(...r.reduce(((t,i)=>{const s=n.get(i);return s&&t.push([e,s]),t}),[]))};for(const e of t.keys())s(e);const r=i.filter((t=>t[1]===e));let o=0;for(;r.length>o;){const e=r.length,t=new Set(r.map((e=>e[0])));for(const e of t)i.filter((t=>t[1]===e)).forEach((e=>{r.includes(e)||r.push(e)}));o=e}const a=function(e){let t=[],n=new Set,i=new Map;for(const t of e)s(t);for(const[e]of i)r(e);return t;function s(e){let[t,n]=e,s=i.get(n);s?s.push(t):i.set(n,[t])}function r(e){if(n.has(e))return;n.add(e);let s=i.get(e);if(s)for(const e of s)r(e);t.push(e)}}(r),l=a.findIndex((t=>t===e));return-1===l?[e]:a.slice(0,l+1)},e.collectStartupPlugins=function(e,t){const n=new Set;for(const t of e.keys())!0===e.get(t).autoStart&&n.add(t);if(t.startPlugins)for(const e of t.startPlugins)n.add(e);if(t.ignorePlugins)for(const e of t.ignorePlugins)n.delete(e);return Array.from(n)}}(Xe||(Xe={}));var rt=n(9988);class ot{constructor(){this._routes=[]}get(e,t){this._add("GET",e,t)}put(e,t){this._add("PUT",e,t)}post(e,t){this._add("POST",e,t)}patch(e,t){this._add("PATCH",e,t)}delete(e,t){this._add("DELETE",e,t)}async route(e){const t=new URL(e.url),{method:n}=e,{pathname:i}=t;for(const s of this._routes){if(s.method!==n)continue;const r=i.match(s.pattern);if(!r)continue;const o=r.slice(1);let a;if("PATCH"===s.method||"PUT"===s.method||"POST"===s.method)try{a=JSON.parse(await e.text())}catch{a=void 0}return s.callback.call(null,{pathname:i,body:a,query:Object.fromEntries(t.searchParams)},...o)}throw new Error("Cannot route "+e.method+" "+e.url)}_add(e,t,n){"string"==typeof t&&(t=new RegExp(t)),this._routes.push({method:e,pattern:t,callback:n})}}class at{constructor(e){this._stream=new p.Stream(this),this._serverSettings=e.serverSettings}async emit(e){}dispose(){}get isDisposed(){return!0}get stream(){return this._stream}get serverSettings(){return this._serverSettings}}class lt extends st{constructor(e){var t;super(e),this.name="JupyterLite Server",this.namespace=this.name,this.version="unknown",this._router=new ot;const n={...u.ServerConnection.makeSettings(),WebSocket:rt.WebSocket,fetch:null!==(t=this.fetch.bind(this))&&void 0!==t?t:void 0};this._serviceManager=new u.ServiceManager({standby:"never",serverSettings:n,events:new at({serverSettings:n})})}get router(){return this._router}get serviceManager(){return this._serviceManager}async fetch(e,t){if(!(e instanceof Request))throw Error("Request info is not a Request");return this._router.route(e)}attachShell(e){}evtResize(e){}registerPluginModule(e){let t=e.default;Object.prototype.hasOwnProperty.call(e,"__esModule")||(t=e),Array.isArray(t)||(t=[t]),t.forEach((e=>{try{this.registerPlugin(e)}catch(e){console.error(e)}}))}registerPluginModules(e){e.forEach((e=>{this.registerPluginModule(e)}))}}var ct=n(4374),ut=n(3570)},3570:(e,t,n)=>{"use strict";n.d(t,{Z:()=>a});var i=n(5082),s=n(4016),r=n(9622),o=n(4374);class a{constructor(e){var t;this._registration=null,this._registrationChanged=new s.Signal(this),this._ready=new i.PromiseDelegate;const n=null!==(t=null==e?void 0:e.workerUrl)&&void 0!==t?t:r.URLExt.join(r.PageConfig.getBaseUrl(),o.o);this.initialize(n).catch(console.warn)}get registrationChanged(){return this._registrationChanged}get enabled(){return null!==this._registration}get ready(){return this._ready.promise}async initialize(e){const{serviceWorker:t}=navigator;let n=null;if(t?t.controller&&(n=await t.getRegistration(t.controller.scriptURL)||null,console.info("JupyterLite ServiceWorker was already registered")):console.warn("ServiceWorkers not supported in this browser"),!n&&t)try{console.info("Registering new JupyterLite ServiceWorker",e),n=await t.register(e),console.info("JupyterLite ServiceWorker was sucessfully registered")}catch(e){console.warn(e),console.warn(`JupyterLite ServiceWorker registration unexpectedly failed: ${e}`)}this.setRegistration(n),n?this._ready.resolve(void 0):this._ready.reject(void 0)}setRegistration(e){this._registration=e,this._registrationChanged.emit(this._registration)}}},4374:(e,t,n)=>{"use strict";n.d(t,{f:()=>r,o:()=>o});var i=n(5082);const s=n.p+"service-worker.js",r=new i.Token("@jupyterlite/server-extension:IServiceWorkerManager"),o=`${s}`.split("/").slice(-1)[0]},5259:(e,t,n)=>{"use strict";var i,s,r;function o(e,t){let n=0;for(const i of e)if(t(i,n++))return i}n.d(t,{RO:()=>i,sE:()=>o}),function(e){function t(e,t,n=0,i=-1){let s,r=e.length;if(0===r)return-1;n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))=n)return;let i=e[t];for(let i=t+1;i0;){let i=a>>1,s=o+i;n(e[s],t)<0?(o=s+1,a-=i+1):a=i}return o},e.upperBound=function(e,t,n,i=0,s=-1){let r=e.length;if(0===r)return 0;let o=i=i<0?Math.max(0,i+r):Math.min(i,r-1),a=(s=s<0?Math.max(0,s+r):Math.min(s,r-1))-i+1;for(;a>0;){let i=a>>1,s=o+i;n(e[s],t)>0?a=i:(o=s+1,a-=i+1)}return o},e.shallowEqual=function(e,t,n){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0,s=e.length;i=o&&(n=s<0?o-1:o),void 0===i?i=s<0?-1:o:i<0?i=Math.max(i+o,s<0?-1:0):i>=o&&(i=s<0?o-1:o),r=s<0&&i>=n||s>0&&n>=i?0:s<0?Math.floor((i-n+1)/s+1):Math.floor((i-n-1)/s+1);let a=[];for(let t=0;t=(i=i<0?Math.max(0,i+s):Math.min(i,s-1)))return;let o=i-n+1;if(t>0?t%=o:t<0&&(t=(t%o+o)%o),0===t)return;let a=n+t;r(e,n,a-1),r(e,a,i),r(e,n,i)},e.fill=function(e,t,n=0,i=-1){let s,r=e.length;if(0!==r){n=n<0?Math.max(0,n+r):Math.min(n,r-1),s=(i=i<0?Math.max(0,i+r):Math.min(i,r-1))t;--n)e[n]=e[n-1];e[t]=n},e.removeAt=o,e.removeFirstOf=function(e,n,i=0,s=-1){let r=t(e,n,i,s);return-1!==r&&o(e,r),r},e.removeLastOf=function(e,t,i=-1,s=0){let r=n(e,t,i,s);return-1!==r&&o(e,r),r},e.removeAllOf=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&e[o]===t||i=n)&&e[o]===t?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r},e.removeFirstWhere=function(e,t,n=0,s=-1){let r,a=i(e,t,n,s);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeLastWhere=function(e,t,n=-1,i=0){let r,a=s(e,t,n,i);return-1!==a&&(r=o(e,a)),{index:a,value:r}},e.removeAllWhere=function(e,t,n=0,i=-1){let s=e.length;if(0===s)return 0;n=n<0?Math.max(0,n+s):Math.min(n,s-1),i=i<0?Math.max(0,i+s):Math.min(i,s-1);let r=0;for(let o=0;o=n&&o<=i&&t(e[o],o)||i=n)&&t(e[o],o)?r++:r>0&&(e[o-r]=e[o]);return r>0&&(e.length=s-r),r}}(i||(i={})),function(e){e.rangeLength=function(e,t,n){return 0===n?1/0:e>t&&n>0||et?1:0}}(r||(r={}))},5082:function(e,t){!function(e){"use strict";e.JSONExt=void 0,function(e){function t(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e}function n(e){return Array.isArray(e)}function i(e,s){if(e===s)return!0;if(t(e)||t(s))return!1;let r=n(e),o=n(s);return r===o&&(r&&o?function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0,s=e.length;n>>0),e[n]=255&t,t>>>=8}e.Random=void 0,(e.Random||(e.Random={})).getRandomValues=(()=>{const e="undefined"!=typeof window&&(window.crypto||window.msCrypto)||null;return e&&"function"==typeof e.getRandomValues?function(t){return e.getRandomValues(t)}:t})(),e.UUID=void 0,(e.UUID||(e.UUID={})).uuid4=function(e){const t=new Uint8Array(16),n=new Array(256);for(let e=0;e<16;++e)n[e]="0"+e.toString(16);for(let e=16;e<256;++e)n[e]=e.toString(16);return function(){return e(t),t[6]=64|15&t[6],t[8]=128|63&t[8],n[t[0]]+n[t[1]]+n[t[2]]+n[t[3]]+"-"+n[t[4]]+n[t[5]]+"-"+n[t[6]]+n[t[7]]+"-"+n[t[8]]+n[t[9]]+"-"+n[t[10]]+n[t[11]]+n[t[12]]+n[t[13]]+n[t[14]]+n[t[15]]}}(e.Random.getRandomValues),e.MimeData=class{constructor(){this._types=[],this._values=[]}types(){return this._types.slice()}hasData(e){return-1!==this._types.indexOf(e)}getData(e){let t=this._types.indexOf(e);return-1!==t?this._values[t]:void 0}setData(e,t){this.clearData(e),this._types.push(e),this._values.push(t)}clearData(e){let t=this._types.indexOf(e);-1!==t&&(this._types.splice(t,1),this._values.splice(t,1))}clear(){this._types.length=0,this._values.length=0}},e.PromiseDelegate=class{constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){(0,this._resolve)(e)}reject(e){(0,this._reject)(e)}},e.Token=class{constructor(e,t){this.name=e,this.description=null!=t?t:"",this._tokenStructuralPropertyT=null}}}(t)},4016:(e,t,n)=>{"use strict";n.r(t),n.d(t,{Signal:()=>o,Stream:()=>a});var i,s=n(5259),r=n(5082);class o{constructor(e){this.sender=e}connect(e,t){return i.connect(this,e,t)}disconnect(e,t){return i.disconnect(this,e,t)}emit(e){i.emit(this,e)}}!function(e){e.disconnectBetween=function(e,t){i.disconnectBetween(e,t)},e.disconnectSender=function(e){i.disconnectSender(e)},e.disconnectReceiver=function(e){i.disconnectReceiver(e)},e.disconnectAll=function(e){i.disconnectAll(e)},e.clearData=function(e){i.disconnectAll(e)},e.getExceptionHandler=function(){return i.exceptionHandler},e.setExceptionHandler=function(e){let t=i.exceptionHandler;return i.exceptionHandler=e,t}}(o||(o={}));class a extends o{constructor(){super(...arguments),this._pending=new r.PromiseDelegate}async*[Symbol.asyncIterator](){let e=this._pending;for(;;)try{const{args:t,next:n}=await e.promise;e=n,yield t}catch(e){return}}emit(e){const t=this._pending,n=this._pending=new r.PromiseDelegate;t.resolve({args:e,next:n}),super.emit(e)}stop(){this._pending.promise.catch((()=>{})),this._pending.reject("stop"),this._pending=new r.PromiseDelegate}}!function(e){function t(e){let t=i.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.thisArg||e.slot;e.signal=null,u(r.get(t))}u(t)}}function n(e){let t=r.get(e);if(t&&0!==t.length){for(const e of t){if(!e.signal)continue;let t=e.signal.sender;e.signal=null,u(i.get(t))}u(t)}}e.exceptionHandler=e=>{console.error(e)},e.connect=function(e,t,n){n=n||void 0;let s=i.get(e.sender);if(s||(s=[],i.set(e.sender,s)),l(s,e,t,n))return!1;let o=n||t,a=r.get(o);a||(a=[],r.set(o,a));let c={signal:e,slot:t,thisArg:n};return s.push(c),a.push(c),!0},e.disconnect=function(e,t,n){n=n||void 0;let s=i.get(e.sender);if(!s||0===s.length)return!1;let o=l(s,e,t,n);if(!o)return!1;let a=n||t,c=r.get(a);return o.signal=null,u(s),u(c),!0},e.disconnectBetween=function(e,t){let n=i.get(e);if(!n||0===n.length)return;let s=r.get(t);if(s&&0!==s.length){for(const t of s)t.signal&&t.signal.sender===e&&(t.signal=null);u(n),u(s)}},e.disconnectSender=t,e.disconnectReceiver=n,e.disconnectAll=function(e){t(e),n(e)},e.emit=function(e,t){let n=i.get(e.sender);if(n&&0!==n.length)for(let i=0,s=n.length;ie.signal===t&&e.slot===n&&e.thisArg===i))}function c(t,n){let{signal:i,slot:s,thisArg:r}=t;try{s.call(r,i.sender,n)}catch(t){e.exceptionHandler(t)}}function u(e){0===o.size&&a(d),o.add(e)}function d(){o.forEach(h),o.clear()}function h(e){s.RO.removeAllWhere(e,p)}function p(e){return null===e.signal}}(i||(i={}))},9146:e=>{"use strict";function t(){this._types=Object.create(null),this._extensions=Object.create(null);for(let e=0;e{"use strict";let i=n(9146);e.exports=new i(n(4415),n(3014))},3014:e=>{e.exports={"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}},4415:e=>{e.exports={"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}},1173:e=>{e.exports={}}},__webpack_module_cache__={},leafPrototypes,getProto,inProgress,dataWebpackPrefix;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.m=__webpack_modules__,__webpack_require__.amdO={},__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var n=Object.create(null);__webpack_require__.r(n);var i={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;"object"==typeof s&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach((t=>i[t]=()=>e[t]));return i.default=()=>e,__webpack_require__.d(n,i),n},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce(((t,n)=>(__webpack_require__.f[n](e,t),t)),[])),__webpack_require__.u=e=>e+".thebe-lite.min.js",__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),inProgress={},dataWebpackPrefix="thebe-lite:",__webpack_require__.l=(e,t,n,i)=>{if(inProgress[e])inProgress[e].push(t);else{var s,r;if(void 0!==n)for(var o=document.getElementsByTagName("script"),a=0;a{s.onerror=s.onload=null,clearTimeout(u);var i=inProgress[e];if(delete inProgress[e],s.parentNode&&s.parentNode.removeChild(s),i&&i.forEach((e=>e(n))),t)return t(n)},u=setTimeout(c.bind(null,void 0,{type:"timeout",target:s}),12e4);s.onerror=c.bind(null,s.onerror),s.onload=c.bind(null,s.onload),r&&document.head.appendChild(s)}},__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;__webpack_require__.g.importScripts&&(e=__webpack_require__.g.location+"");var t=__webpack_require__.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),__webpack_require__.p=e})(),(()=>{__webpack_require__.b=document.baseURI||self.location.href;var e={143:0};__webpack_require__.f.j=(t,n)=>{var i=__webpack_require__.o(e,t)?e[t]:void 0;if(0!==i)if(i)n.push(i[2]);else{var s=new Promise(((n,s)=>i=e[t]=[n,s]));n.push(i[2]=s);var r=__webpack_require__.p+__webpack_require__.u(t),o=new Error;__webpack_require__.l(r,(n=>{if(__webpack_require__.o(e,t)&&(0!==(i=e[t])&&(e[t]=void 0),i)){var s=n&&("load"===n.type?"missing":n.type),r=n&&n.target&&n.target.src;o.message="Loading chunk "+t+" failed.\n("+s+": "+r+")",o.name="ChunkLoadError",o.type=s,o.request=r,i[1](o)}}),"chunk-"+t,t)}};var t=(t,n)=>{var i,s,[r,o,a]=n,l=0;if(r.some((t=>0!==e[t]))){for(i in o)__webpack_require__.o(o,i)&&(__webpack_require__.m[i]=o[i]);a&&a(__webpack_require__)}for(t&&t(n);l {\n if (response.status !== 200) {\n throw new serverconnection_1.ServerConnection.ResponseError(response);\n }\n return response.json();\n })\n .then(data => {\n if (typeof data.status !== 'string') {\n throw new Error('Invalid data');\n }\n if (typeof data.message !== 'string') {\n throw new Error('Invalid data');\n }\n return data;\n });\n }\n /**\n * Build the application.\n */\n build() {\n const { _url, serverSettings } = this;\n const init = { method: 'POST' };\n const promise = serverconnection_1.ServerConnection.makeRequest(_url, init, serverSettings);\n return promise.then(response => {\n if (response.status === 400) {\n throw new serverconnection_1.ServerConnection.ResponseError(response, 'Build aborted');\n }\n if (response.status !== 200) {\n const message = `Build failed with ${response.status}.\n\n If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').\n\n If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;\n throw new serverconnection_1.ServerConnection.ResponseError(response, message);\n }\n });\n }\n /**\n * Cancel an active build.\n */\n cancel() {\n const { _url, serverSettings } = this;\n const init = { method: 'DELETE' };\n const promise = serverconnection_1.ServerConnection.makeRequest(_url, init, serverSettings);\n return promise.then(response => {\n if (response.status !== 204) {\n throw new serverconnection_1.ServerConnection.ResponseError(response);\n }\n });\n }\n}\nexports.BuildManager = BuildManager;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ConfigWithDefaults = exports.ConfigSection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst __1 = require(\"..\");\n/**\n * The url for the config service.\n */\nconst SERVICE_CONFIG_URL = 'api/config';\n/**\n * The namespace for ConfigSection statics.\n */\nvar ConfigSection;\n(function (ConfigSection) {\n /**\n * Create a config section.\n *\n * @returns A Promise that is fulfilled with the config section is loaded.\n */\n function create(options) {\n const section = new DefaultConfigSection(options);\n return section.load().then(() => {\n return section;\n });\n }\n ConfigSection.create = create;\n})(ConfigSection = exports.ConfigSection || (exports.ConfigSection = {}));\n/**\n * Implementation of the Configurable data section.\n */\nclass DefaultConfigSection {\n /**\n * Construct a new config section.\n */\n constructor(options) {\n var _a;\n this._url = 'unknown';\n const settings = (this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings());\n this._url = coreutils_1.URLExt.join(settings.baseUrl, SERVICE_CONFIG_URL, encodeURIComponent(options.name));\n }\n /**\n * Get the data for this section.\n */\n get data() {\n return this._data;\n }\n /**\n * Load the initial data for this section.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async load() {\n const response = await __1.ServerConnection.makeRequest(this._url, {}, this.serverSettings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._data = await response.json();\n }\n /**\n * Modify the stored config values.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * Updates the local data immediately, sends the change to the server,\n * and updates the local data with the response, and fulfils the promise\n * with that data.\n */\n async update(newdata) {\n this._data = { ...this._data, ...newdata };\n const init = {\n method: 'PATCH',\n body: JSON.stringify(newdata)\n };\n const response = await __1.ServerConnection.makeRequest(this._url, init, this.serverSettings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._data = await response.json();\n return this._data;\n }\n}\n/**\n * Configurable object with defaults.\n */\nclass ConfigWithDefaults {\n /**\n * Create a new config with defaults.\n */\n constructor(options) {\n var _a, _b;\n this._className = '';\n this._section = options.section;\n this._defaults = (_a = options.defaults) !== null && _a !== void 0 ? _a : {};\n this._className = (_b = options.className) !== null && _b !== void 0 ? _b : '';\n }\n /**\n * Get data from the config section or fall back to defaults.\n */\n get(key) {\n const data = this._classData();\n return key in data ? data[key] : this._defaults[key];\n }\n /**\n * Set a config value.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * Sends the update to the server, and changes our local copy of the data\n * immediately.\n */\n set(key, value) {\n const d = {};\n d[key] = value;\n if (this._className) {\n const d2 = {};\n d2[this._className] = d;\n return this._section.update(d2);\n }\n else {\n return this._section.update(d);\n }\n }\n /**\n * Get data from the Section with our classname, if available.\n *\n * #### Notes\n * If we have no classname, get all of the data in the Section\n */\n _classData() {\n const data = this._section.data;\n if (this._className && this._className in data) {\n return data[this._className];\n }\n return data;\n }\n}\nexports.ConfigWithDefaults = ConfigWithDefaults;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Drive = exports.ContentsManager = exports.Contents = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst validate = __importStar(require(\"./validate\"));\n/**\n * The url for the default drive service.\n */\nconst SERVICE_DRIVE_URL = 'api/contents';\n/**\n * The url for the file access.\n */\nconst FILES_URL = 'files';\n/**\n * A namespace for contents interfaces.\n */\nvar Contents;\n(function (Contents) {\n /**\n * Validates an IModel, throwing an error if it does not pass.\n */\n function validateContentsModel(contents) {\n validate.validateContentsModel(contents);\n }\n Contents.validateContentsModel = validateContentsModel;\n /**\n * Validates an ICheckpointModel, throwing an error if it does not pass.\n */\n function validateCheckpointModel(checkpoint) {\n validate.validateCheckpointModel(checkpoint);\n }\n Contents.validateCheckpointModel = validateCheckpointModel;\n})(Contents = exports.Contents || (exports.Contents = {}));\n/**\n * A contents manager that passes file operations to the server.\n * Multiple servers implementing the `IDrive` interface can be\n * attached to the contents manager, so that the same session can\n * perform file operations on multiple backends.\n *\n * This includes checkpointing with the normal file operations.\n */\nclass ContentsManager {\n /**\n * Construct a new contents manager object.\n *\n * @param options - The options used to initialize the object.\n */\n constructor(options = {}) {\n var _a, _b;\n this._isDisposed = false;\n this._additionalDrives = new Map();\n this._fileChanged = new signaling_1.Signal(this);\n const serverSettings = (this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings());\n this._defaultDrive = (_b = options.defaultDrive) !== null && _b !== void 0 ? _b : new Drive({ serverSettings });\n this._defaultDrive.fileChanged.connect(this._onFileChanged, this);\n }\n /**\n * A signal emitted when a file operation takes place.\n */\n get fileChanged() {\n return this._fileChanged;\n }\n /**\n * Test whether the manager has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * Add an `IDrive` to the manager.\n */\n addDrive(drive) {\n this._additionalDrives.set(drive.name, drive);\n drive.fileChanged.connect(this._onFileChanged, this);\n }\n /**\n * Given a path, get a shared model factory from the\n * relevant backend. Returns `null` if the backend\n * does not provide one.\n */\n getSharedModelFactory(path) {\n var _a;\n const [drive] = this._driveForPath(path);\n return (_a = drive === null || drive === void 0 ? void 0 : drive.sharedModelFactory) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the local part of it.\n *\n * @param path: the path.\n *\n * @returns The local part of the path.\n */\n localPath(path) {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1 || !this._additionalDrives.has(firstParts[0])) {\n return coreutils_1.PathExt.removeSlash(path);\n }\n return coreutils_1.PathExt.join(firstParts.slice(1).join(':'), ...parts.slice(1));\n }\n /**\n * Normalize a global path. Reduces '..' and '.' parts, and removes\n * leading slashes from the local part of the path, while retaining\n * the drive name if it exists.\n *\n * @param path: the path.\n *\n * @returns The normalized path.\n */\n normalize(path) {\n const parts = path.split(':');\n if (parts.length === 1) {\n return coreutils_1.PathExt.normalize(path);\n }\n return `${parts[0]}:${coreutils_1.PathExt.normalize(parts.slice(1).join(':'))}`;\n }\n /**\n * Resolve a global path, starting from the root path. Behaves like\n * posix-path.resolve, with 3 differences:\n * - will never prepend cwd\n * - if root has a drive name, the result is prefixed with \":\"\n * - before adding drive name, leading slashes are removed\n *\n * @param path: the path.\n *\n * @returns The normalized path.\n */\n resolvePath(root, path) {\n const driveName = this.driveName(root);\n const localPath = this.localPath(root);\n const resolved = coreutils_1.PathExt.resolve('/', localPath, path);\n return driveName ? `${driveName}:${resolved}` : resolved;\n }\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the name of the drive. If the path is missing\n * a drive portion, returns an empty string.\n *\n * @param path: the path.\n *\n * @returns The drive name for the path, or the empty string.\n */\n driveName(path) {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1) {\n return '';\n }\n if (this._additionalDrives.has(firstParts[0])) {\n return firstParts[0];\n }\n return '';\n }\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n *\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n get(path, options) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.get(localPath, options).then(contentsModel => {\n const listing = [];\n if (contentsModel.type === 'directory' && contentsModel.content) {\n for (const item of contentsModel.content) {\n listing.push({ ...item, path: this._toGlobalPath(drive, item.path) });\n }\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive, localPath),\n content: listing,\n serverPath: contentsModel.path\n };\n }\n else {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive, localPath),\n serverPath: contentsModel.path\n };\n }\n });\n }\n /**\n * Get an encoded download url given a file path.\n *\n * @param path - An absolute POSIX file path on the server.\n *\n * #### Notes\n * It is expected that the path contains no relative paths.\n *\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.getDownloadUrl(localPath);\n }\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n */\n newUntitled(options = {}) {\n if (options.path) {\n const globalPath = this.normalize(options.path);\n const [drive, localPath] = this._driveForPath(globalPath);\n return drive\n .newUntitled({ ...options, path: localPath })\n .then(contentsModel => {\n return {\n ...contentsModel,\n path: coreutils_1.PathExt.join(globalPath, contentsModel.name),\n serverPath: contentsModel.path\n };\n });\n }\n else {\n return this._defaultDrive.newUntitled(options);\n }\n }\n /**\n * Delete a file.\n *\n * @param path - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n */\n delete(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.delete(localPath);\n }\n /**\n * Rename a file or directory.\n *\n * @param path - The original file path.\n *\n * @param newPath - The new file path.\n *\n * @returns A promise which resolves with the new file contents model when\n * the file is renamed.\n */\n rename(path, newPath) {\n const [drive1, path1] = this._driveForPath(path);\n const [drive2, path2] = this._driveForPath(newPath);\n if (drive1 !== drive2) {\n throw Error('ContentsManager: renaming files must occur within a Drive');\n }\n return drive1.rename(path1, path2).then(contentsModel => {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive1, path2),\n serverPath: contentsModel.path\n };\n });\n }\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n */\n save(path, options = {}) {\n const globalPath = this.normalize(path);\n const [drive, localPath] = this._driveForPath(path);\n return drive\n .save(localPath, { ...options, path: localPath })\n .then(contentsModel => {\n return {\n ...contentsModel,\n path: globalPath,\n serverPath: contentsModel.path\n };\n });\n }\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n copy(fromFile, toDir) {\n const [drive1, path1] = this._driveForPath(fromFile);\n const [drive2, path2] = this._driveForPath(toDir);\n if (drive1 === drive2) {\n return drive1.copy(path1, path2).then(contentsModel => {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive1, contentsModel.path),\n serverPath: contentsModel.path\n };\n });\n }\n else {\n throw Error('Copying files between drives is not currently implemented');\n }\n }\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n createCheckpoint(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.createCheckpoint(localPath);\n }\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n listCheckpoints(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.listCheckpoints(localPath);\n }\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n restoreCheckpoint(path, checkpointID) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.restoreCheckpoint(localPath, checkpointID);\n }\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n deleteCheckpoint(path, checkpointID) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.deleteCheckpoint(localPath, checkpointID);\n }\n /**\n * Given a drive and a local path, construct a fully qualified\n * path. The inverse of `_driveForPath`.\n *\n * @param drive: an `IDrive`.\n *\n * @param localPath: the local path on the drive.\n *\n * @returns the fully qualified path.\n */\n _toGlobalPath(drive, localPath) {\n if (drive === this._defaultDrive) {\n return coreutils_1.PathExt.removeSlash(localPath);\n }\n else {\n return `${drive.name}:${coreutils_1.PathExt.removeSlash(localPath)}`;\n }\n }\n /**\n * Given a path, get the `IDrive to which it refers,\n * where the path satisfies the pattern\n * `'driveName:path/to/file'`. If there is no `driveName`\n * prepended to the path, it returns the default drive.\n *\n * @param path: a path to a file.\n *\n * @returns A tuple containing an `IDrive` object for the path,\n * and a local path for that drive.\n */\n _driveForPath(path) {\n const driveName = this.driveName(path);\n const localPath = this.localPath(path);\n if (driveName) {\n return [this._additionalDrives.get(driveName), localPath];\n }\n else {\n return [this._defaultDrive, localPath];\n }\n }\n /**\n * Respond to fileChanged signals from the drives attached to\n * the manager. This prepends the drive name to the path if necessary,\n * and then forwards the signal.\n */\n _onFileChanged(sender, args) {\n var _a, _b;\n if (sender === this._defaultDrive) {\n this._fileChanged.emit(args);\n }\n else {\n let newValue = null;\n let oldValue = null;\n if ((_a = args.newValue) === null || _a === void 0 ? void 0 : _a.path) {\n newValue = {\n ...args.newValue,\n path: this._toGlobalPath(sender, args.newValue.path)\n };\n }\n if ((_b = args.oldValue) === null || _b === void 0 ? void 0 : _b.path) {\n oldValue = {\n ...args.oldValue,\n path: this._toGlobalPath(sender, args.oldValue.path)\n };\n }\n this._fileChanged.emit({\n type: args.type,\n newValue,\n oldValue\n });\n }\n }\n}\nexports.ContentsManager = ContentsManager;\n/**\n * A default implementation for an `IDrive`, talking to the\n * server using the Jupyter REST API.\n */\nclass Drive {\n /**\n * Construct a new contents manager object.\n *\n * @param options - The options used to initialize the object.\n */\n constructor(options = {}) {\n var _a, _b, _c;\n this._isDisposed = false;\n this._fileChanged = new signaling_1.Signal(this);\n this.name = (_a = options.name) !== null && _a !== void 0 ? _a : 'Default';\n this._apiEndpoint = (_b = options.apiEndpoint) !== null && _b !== void 0 ? _b : SERVICE_DRIVE_URL;\n this.serverSettings =\n (_c = options.serverSettings) !== null && _c !== void 0 ? _c : __1.ServerConnection.makeSettings();\n }\n /**\n * A signal emitted when a file operation takes place.\n */\n get fileChanged() {\n return this._fileChanged;\n }\n /**\n * Test whether the manager has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * Get a file or directory.\n *\n * @param localPath: The path to the file.\n *\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n *\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async get(localPath, options) {\n let url = this._getUrl(localPath);\n if (options) {\n // The notebook type cannot take an format option.\n if (options.type === 'notebook') {\n delete options['format'];\n }\n const content = options.content ? '1' : '0';\n const params = { ...options, content };\n url += coreutils_1.URLExt.objectToQueryString(params);\n }\n const settings = this.serverSettings;\n const response = await __1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n return data;\n }\n /**\n * Get an encoded download url given a file path.\n *\n * @param localPath - An absolute POSIX file path on the server.\n *\n * #### Notes\n * It is expected that the path contains no relative paths.\n *\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(localPath) {\n const baseUrl = this.serverSettings.baseUrl;\n let url = coreutils_1.URLExt.join(baseUrl, FILES_URL, coreutils_1.URLExt.encodeParts(localPath));\n const xsrfTokenMatch = document.cookie.match('\\\\b_xsrf=([^;]*)\\\\b');\n if (xsrfTokenMatch) {\n const fullUrl = new URL(url);\n fullUrl.searchParams.append('_xsrf', xsrfTokenMatch[1]);\n url = fullUrl.toString();\n }\n return Promise.resolve(url);\n }\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async newUntitled(options = {}) {\n var _a;\n let body = '{}';\n if (options) {\n if (options.ext) {\n options.ext = Private.normalizeExtension(options.ext);\n }\n body = JSON.stringify(options);\n }\n const settings = this.serverSettings;\n const url = this._getUrl((_a = options.path) !== null && _a !== void 0 ? _a : '');\n const init = {\n method: 'POST',\n body\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n /**\n * Delete a file.\n *\n * @param localPath - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async delete(localPath) {\n const url = this._getUrl(localPath);\n const settings = this.serverSettings;\n const init = { method: 'DELETE' };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n // TODO: update IPEP27 to specify errors more precisely, so\n // that error types can be detected here with certainty.\n if (response.status !== 204) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._fileChanged.emit({\n type: 'delete',\n oldValue: { path: localPath },\n newValue: null\n });\n }\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file contents model when\n * the file is renamed.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async rename(oldLocalPath, newLocalPath) {\n const settings = this.serverSettings;\n const url = this._getUrl(oldLocalPath);\n const init = {\n method: 'PATCH',\n body: JSON.stringify({ path: newLocalPath })\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'rename',\n oldValue: { path: oldLocalPath },\n newValue: data\n });\n return data;\n }\n /**\n * Save a file.\n *\n * @param localPath - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n *\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async save(localPath, options = {}) {\n const settings = this.serverSettings;\n const url = this._getUrl(localPath);\n const init = {\n method: 'PUT',\n body: JSON.stringify(options)\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n // will return 200 for an existing file and 201 for a new file\n if (response.status !== 200 && response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'save',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n /**\n * Copy a file into a given directory.\n *\n * @param localPath - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n *\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async copy(fromFile, toDir) {\n const settings = this.serverSettings;\n const url = this._getUrl(toDir);\n const init = {\n method: 'POST',\n body: JSON.stringify({ copy_from: fromFile })\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n /**\n * Create a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async createCheckpoint(localPath) {\n const url = this._getUrl(localPath, 'checkpoints');\n const init = { method: 'POST' };\n const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);\n if (response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateCheckpointModel(data);\n return data;\n }\n /**\n * List available checkpoints for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async listCheckpoints(localPath) {\n const url = this._getUrl(localPath, 'checkpoints');\n const response = await __1.ServerConnection.makeRequest(url, {}, this.serverSettings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid Checkpoint list');\n }\n for (let i = 0; i < data.length; i++) {\n validate.validateCheckpointModel(data[i]);\n }\n return data;\n }\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async restoreCheckpoint(localPath, checkpointID) {\n const url = this._getUrl(localPath, 'checkpoints', checkpointID);\n const init = { method: 'POST' };\n const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);\n if (response.status !== 204) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n }\n /**\n * Delete a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async deleteCheckpoint(localPath, checkpointID) {\n const url = this._getUrl(localPath, 'checkpoints', checkpointID);\n const init = { method: 'DELETE' };\n const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);\n if (response.status !== 204) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n }\n /**\n * Get a REST url for a file given a path.\n */\n _getUrl(...args) {\n const parts = args.map(path => coreutils_1.URLExt.encodeParts(path));\n const baseUrl = this.serverSettings.baseUrl;\n return coreutils_1.URLExt.join(baseUrl, this._apiEndpoint, ...parts);\n }\n}\nexports.Drive = Drive;\n/**\n * A namespace for module private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * Adds a leading dot if not present and converts to lower case.\n */\n function normalizeExtension(extension) {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n Private.normalizeExtension = normalizeExtension;\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateCheckpointModel = exports.validateContentsModel = void 0;\nconst validate_1 = require(\"../validate\");\n/**\n * Validate an `Contents.IModel` object.\n */\nfunction validateContentsModel(model) {\n (0, validate_1.validateProperty)(model, 'name', 'string');\n (0, validate_1.validateProperty)(model, 'path', 'string');\n (0, validate_1.validateProperty)(model, 'type', 'string');\n (0, validate_1.validateProperty)(model, 'created', 'string');\n (0, validate_1.validateProperty)(model, 'last_modified', 'string');\n (0, validate_1.validateProperty)(model, 'mimetype', 'object');\n (0, validate_1.validateProperty)(model, 'content', 'object');\n (0, validate_1.validateProperty)(model, 'format', 'object');\n}\nexports.validateContentsModel = validateContentsModel;\n/**\n * Validate an `Contents.ICheckpointModel` object.\n */\nfunction validateCheckpointModel(model) {\n (0, validate_1.validateProperty)(model, 'id', 'string');\n (0, validate_1.validateProperty)(model, 'last_modified', 'string');\n}\nexports.validateCheckpointModel = validateCheckpointModel;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EventManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the jupyter-server events service.\n */\nconst SERVICE_EVENTS_URL = 'api/events';\n/**\n * The events API service manager.\n */\nclass EventManager {\n /**\n * Create a new event manager.\n */\n constructor(options = {}) {\n var _a;\n this._socket = null;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n // If subscription fails, the poll attempts to reconnect and backs off.\n this._poll = new polling_1.Poll({ factory: () => this._subscribe() });\n this._stream = new signaling_1.Stream(this);\n // Subscribe to the events socket.\n void this._poll.start();\n }\n /**\n * Whether the event manager is disposed.\n */\n get isDisposed() {\n return this._poll.isDisposed;\n }\n /**\n * An event stream that emits and yields each new event.\n */\n get stream() {\n return this._stream;\n }\n /**\n * Dispose the event manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n // Clean up poll.\n this._poll.dispose();\n // Clean up socket.\n const socket = this._socket;\n if (socket) {\n this._socket = null;\n socket.onopen = () => undefined;\n socket.onerror = () => undefined;\n socket.onmessage = () => undefined;\n socket.onclose = () => undefined;\n socket.close();\n }\n // Clean up stream.\n signaling_1.Signal.clearData(this);\n this._stream.stop();\n }\n /**\n * Post an event request to be emitted by the event bus.\n */\n async emit(event) {\n const { serverSettings } = this;\n const { baseUrl, token } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const url = coreutils_1.URLExt.join(baseUrl, SERVICE_EVENTS_URL) +\n (token ? `?token=${token}` : '');\n const init = { body: JSON.stringify(event), method: 'POST' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n throw new ResponseError(response);\n }\n }\n /**\n * Subscribe to event bus emissions.\n */\n _subscribe() {\n return new Promise((_, reject) => {\n if (this.isDisposed) {\n return;\n }\n const { token, WebSocket, wsUrl } = this.serverSettings;\n const url = coreutils_1.URLExt.join(wsUrl, SERVICE_EVENTS_URL, 'subscribe') +\n (token ? `?token=${encodeURIComponent(token)}` : '');\n const socket = (this._socket = new WebSocket(url));\n const stream = this._stream;\n socket.onclose = () => reject(new Error('EventManager socket closed'));\n socket.onmessage = msg => msg.data && stream.emit(JSON.parse(msg.data));\n });\n }\n}\nexports.EventManager = EventManager;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module services\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./basemanager\"), exports);\n__exportStar(require(\"./config\"), exports);\n__exportStar(require(\"./contents\"), exports);\n__exportStar(require(\"./event\"), exports);\n__exportStar(require(\"./kernel\"), exports);\n__exportStar(require(\"./kernelspec\"), exports);\n__exportStar(require(\"./manager\"), exports);\n__exportStar(require(\"./serverconnection\"), exports);\n__exportStar(require(\"./session\"), exports);\n__exportStar(require(\"./setting\"), exports);\n__exportStar(require(\"./terminal\"), exports);\n__exportStar(require(\"./user\"), exports);\n__exportStar(require(\"./workspace\"), exports);\n__exportStar(require(\"./nbconvert\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CommHandler = void 0;\nconst disposable_1 = require(\"@lumino/disposable\");\nconst KernelMessage = __importStar(require(\"./messages\"));\n/**\n * Comm channel handler.\n */\nclass CommHandler extends disposable_1.DisposableDelegate {\n /**\n * Construct a new comm channel.\n */\n constructor(target, id, kernel, disposeCb) {\n super(disposeCb);\n this._target = '';\n this._id = '';\n this._id = id;\n this._target = target;\n this._kernel = kernel;\n }\n /**\n * The unique id for the comm channel.\n */\n get commId() {\n return this._id;\n }\n /**\n * The target name for the comm channel.\n */\n get targetName() {\n return this._target;\n }\n /**\n * Get the callback for a comm close event.\n *\n * #### Notes\n * This is called when the comm is closed from either the server or client.\n *\n * **See also:** [[ICommClose]], [[close]]\n */\n get onClose() {\n return this._onClose;\n }\n /**\n * Set the callback for a comm close event.\n *\n * #### Notes\n * This is called when the comm is closed from either the server or client. If\n * the function returns a promise, and the kernel was closed from the server,\n * kernel message processing will pause until the returned promise is\n * fulfilled.\n *\n * **See also:** [[close]]\n */\n set onClose(cb) {\n this._onClose = cb;\n }\n /**\n * Get the callback for a comm message received event.\n */\n get onMsg() {\n return this._onMsg;\n }\n /**\n * Set the callback for a comm message received event.\n *\n * #### Notes\n * This is called when a comm message is received. If the function returns a\n * promise, kernel message processing will pause until it is fulfilled.\n */\n set onMsg(cb) {\n this._onMsg = cb;\n }\n /**\n * Open a comm with optional data and metadata.\n *\n * #### Notes\n * This sends a `comm_open` message to the server.\n *\n * **See also:** [[ICommOpen]]\n */\n open(data, metadata, buffers = []) {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot open');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_open',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n target_name: this._target,\n data: data !== null && data !== void 0 ? data : {}\n },\n metadata,\n buffers\n });\n return this._kernel.sendShellMessage(msg, false, true);\n }\n /**\n * Send a `comm_msg` message to the kernel.\n *\n * #### Notes\n * This is a no-op if the comm has been closed.\n *\n * **See also:** [[ICommMsg]]\n */\n send(data, metadata, buffers = [], disposeOnDone = true) {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot send');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_msg',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data\n },\n metadata,\n buffers\n });\n return this._kernel.sendShellMessage(msg, false, disposeOnDone);\n }\n /**\n * Close the comm.\n *\n * #### Notes\n * This will send a `comm_close` message to the kernel, and call the\n * `onClose` callback if set.\n *\n * This is a no-op if the comm is already closed.\n *\n * **See also:** [[ICommClose]], [[onClose]]\n */\n close(data, metadata, buffers = []) {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot close');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_close',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data !== null && data !== void 0 ? data : {}\n },\n metadata,\n buffers\n });\n const future = this._kernel.sendShellMessage(msg, false, true);\n const onClose = this._onClose;\n if (onClose) {\n const ioMsg = KernelMessage.createMessage({\n msgType: 'comm_close',\n channel: 'iopub',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data !== null && data !== void 0 ? data : {}\n },\n metadata,\n buffers\n });\n // In the future, we may want to communicate back to the user the possible\n // promise returned from onClose.\n void onClose(ioMsg);\n }\n this.dispose();\n return future;\n }\n}\nexports.CommHandler = CommHandler;\n//# sourceMappingURL=comm.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelConnection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst comm_1 = require(\"./comm\");\nconst KernelMessage = __importStar(require(\"./messages\"));\nconst future_1 = require(\"./future\");\nconst serialize_1 = require(\"./serialize\");\nconst validate = __importStar(require(\"./validate\"));\nconst kernelspec_1 = require(\"../kernelspec\");\nconst restapi = __importStar(require(\"./restapi\"));\nconst KERNEL_INFO_TIMEOUT = 3000;\nconst RESTARTING_KERNEL_SESSION = '_RESTARTING_';\nconst STARTING_KERNEL_SESSION = '';\n/**\n * Implementation of the Kernel object.\n *\n * #### Notes\n * Messages from the server are handled in the order they were received and\n * asynchronously. Any message handler can return a promise, and message\n * handling will pause until the promise is fulfilled.\n */\nclass KernelConnection {\n /**\n * Construct a kernel object.\n */\n constructor(options) {\n var _a, _b, _c, _d;\n /**\n * Create the kernel websocket connection and add socket status handlers.\n */\n this._createSocket = (useProtocols = true) => {\n this._errorIfDisposed();\n // Make sure the socket is clear\n this._clearSocket();\n // Update the connection status to reflect opening a new connection.\n this._updateConnectionStatus('connecting');\n const settings = this.serverSettings;\n const partialUrl = coreutils_1.URLExt.join(settings.wsUrl, restapi.KERNEL_SERVICE_URL, encodeURIComponent(this._id));\n // Strip any authentication from the display string.\n const display = partialUrl.replace(/^((?:\\w+:)?\\/\\/)(?:[^@\\/]+@)/, '$1');\n console.debug(`Starting WebSocket: ${display}`);\n let url = coreutils_1.URLExt.join(partialUrl, 'channels?session_id=' + encodeURIComponent(this._clientId));\n // If token authentication is in use.\n const token = settings.token;\n if (settings.appendToken && token !== '') {\n url = url + `&token=${encodeURIComponent(token)}`;\n }\n // Try opening the websocket with our list of subprotocols.\n // If the server doesn't handle subprotocols,\n // the accepted protocol will be ''.\n // But we cannot send '' as a subprotocol, so if connection fails,\n // reconnect without subprotocols.\n const supportedProtocols = useProtocols ? this._supportedProtocols : [];\n this._ws = new settings.WebSocket(url, supportedProtocols);\n // Ensure incoming binary messages are not Blobs\n this._ws.binaryType = 'arraybuffer';\n let alreadyCalledOnclose = false;\n const getKernelModel = async (evt) => {\n var _a, _b;\n if (this._isDisposed) {\n return;\n }\n this._reason = '';\n this._model = undefined;\n try {\n const model = await restapi.getKernelModel(this._id, settings);\n this._model = model;\n if ((model === null || model === void 0 ? void 0 : model.execution_state) === 'dead') {\n this._updateStatus('dead');\n }\n else {\n this._onWSClose(evt);\n }\n }\n catch (err) {\n // Try again, if there is a network failure\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof __1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n const timeout = Private.getRandomIntInclusive(10, 30) * 1e3;\n setTimeout(getKernelModel, timeout, evt);\n }\n else {\n this._reason = 'Kernel died unexpectedly';\n this._updateStatus('dead');\n }\n }\n return;\n };\n const earlyClose = async (evt) => {\n // If the websocket was closed early, that could mean\n // that the kernel is actually dead. Try getting\n // information about the kernel from the API call,\n // if that fails, then assume the kernel is dead,\n // otherwise just follow the typical websocket closed\n // protocol.\n if (alreadyCalledOnclose) {\n return;\n }\n alreadyCalledOnclose = true;\n await getKernelModel(evt);\n return;\n };\n this._ws.onmessage = this._onWSMessage;\n this._ws.onopen = this._onWSOpen;\n this._ws.onclose = earlyClose;\n this._ws.onerror = earlyClose;\n };\n // Make websocket callbacks arrow functions so they bind `this`.\n /**\n * Handle a websocket open event.\n */\n this._onWSOpen = (evt) => {\n if (this._ws.protocol !== '' &&\n !this._supportedProtocols.includes(this._ws.protocol)) {\n console.log('Server selected unknown kernel wire protocol:', this._ws.protocol);\n this._updateStatus('dead');\n throw new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);\n }\n // Remember the kernel wire protocol selected by the server.\n this._selectedProtocol = this._ws.protocol;\n this._ws.onclose = this._onWSClose;\n this._ws.onerror = this._onWSClose;\n this._updateConnectionStatus('connected');\n };\n /**\n * Handle a websocket message, validating and routing appropriately.\n */\n this._onWSMessage = (evt) => {\n // Notify immediately if there is an error with the message.\n let msg;\n try {\n msg = (0, serialize_1.deserialize)(evt.data, this._ws.protocol);\n validate.validateMessage(msg);\n }\n catch (error) {\n error.message = `Kernel message validation error: ${error.message}`;\n // We throw the error so that it bubbles up to the top, and displays the right stack.\n throw error;\n }\n // Update the current kernel session id\n this._kernelSession = msg.header.session;\n // Handle the message asynchronously, in the order received.\n this._msgChain = this._msgChain\n .then(() => {\n // Return so that any promises from handling a message are fulfilled\n // before proceeding to the next message.\n return this._handleMessage(msg);\n })\n .catch(error => {\n // Log any errors in handling the message, thus resetting the _msgChain\n // promise so we can process more messages.\n // Ignore the \"Canceled\" errors that are thrown during kernel dispose.\n if (error.message.startsWith('Canceled future for ')) {\n console.error(error);\n }\n });\n // Emit the message receive signal\n this._anyMessage.emit({ msg, direction: 'recv' });\n };\n /**\n * Handle a websocket close event.\n */\n this._onWSClose = (evt) => {\n if (!this.isDisposed) {\n this._reconnect();\n }\n };\n this._id = '';\n this._name = '';\n this._status = 'unknown';\n this._connectionStatus = 'connecting';\n this._kernelSession = '';\n this._isDisposed = false;\n /**\n * Websocket to communicate with kernel.\n */\n this._ws = null;\n this._username = '';\n this._reconnectLimit = 7;\n this._reconnectAttempt = 0;\n this._reconnectTimeout = null;\n this._supportedProtocols = Object.values(KernelMessage.supportedKernelWebSocketProtocols);\n this._selectedProtocol = '';\n this._futures = new Map();\n this._comms = new Map();\n this._targetRegistry = Object.create(null);\n this._info = new coreutils_2.PromiseDelegate();\n this._pendingMessages = [];\n this._statusChanged = new signaling_1.Signal(this);\n this._connectionStatusChanged = new signaling_1.Signal(this);\n this._disposed = new signaling_1.Signal(this);\n this._iopubMessage = new signaling_1.Signal(this);\n this._anyMessage = new signaling_1.Signal(this);\n this._pendingInput = new signaling_1.Signal(this);\n this._unhandledMessage = new signaling_1.Signal(this);\n this._displayIdToParentIds = new Map();\n this._msgIdToDisplayIds = new Map();\n this._msgChain = Promise.resolve();\n this._hasPendingInput = false;\n this._reason = '';\n this._noOp = () => {\n /* no-op */\n };\n this._name = options.model.name;\n this._id = options.model.id;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings();\n this._clientId = (_b = options.clientId) !== null && _b !== void 0 ? _b : coreutils_2.UUID.uuid4();\n this._username = (_c = options.username) !== null && _c !== void 0 ? _c : '';\n this.handleComms = (_d = options.handleComms) !== null && _d !== void 0 ? _d : true;\n this._createSocket();\n }\n get disposed() {\n return this._disposed;\n }\n /**\n * A signal emitted when the kernel status changes.\n */\n get statusChanged() {\n return this._statusChanged;\n }\n /**\n * A signal emitted when the kernel status changes.\n */\n get connectionStatusChanged() {\n return this._connectionStatusChanged;\n }\n /**\n * A signal emitted for iopub kernel messages.\n *\n * #### Notes\n * This signal is emitted after the iopub message is handled asynchronously.\n */\n get iopubMessage() {\n return this._iopubMessage;\n }\n /**\n * A signal emitted for unhandled kernel message.\n *\n * #### Notes\n * This signal is emitted for a message that was not handled. It is emitted\n * during the asynchronous message handling code.\n */\n get unhandledMessage() {\n return this._unhandledMessage;\n }\n /**\n * The kernel model\n */\n get model() {\n return (this._model || {\n id: this.id,\n name: this.name,\n reason: this._reason\n });\n }\n /**\n * A signal emitted for any kernel message.\n *\n * #### Notes\n * This signal is emitted when a message is received, before it is handled\n * asynchronously.\n *\n * This message is emitted when a message is queued for sending (either in\n * the websocket buffer, or our own pending message buffer). The message may\n * actually be sent across the wire at a later time.\n *\n * The message emitted in this signal should not be modified in any way.\n */\n get anyMessage() {\n return this._anyMessage;\n }\n /**\n * A signal emitted when a kernel has pending inputs from the user.\n */\n get pendingInput() {\n return this._pendingInput;\n }\n /**\n * The id of the server-side kernel.\n */\n get id() {\n return this._id;\n }\n /**\n * The name of the server-side kernel.\n */\n get name() {\n return this._name;\n }\n /**\n * The client username.\n */\n get username() {\n return this._username;\n }\n /**\n * The client unique id.\n */\n get clientId() {\n return this._clientId;\n }\n /**\n * The current status of the kernel.\n */\n get status() {\n return this._status;\n }\n /**\n * The current connection status of the kernel connection.\n */\n get connectionStatus() {\n return this._connectionStatus;\n }\n /**\n * Test whether the kernel has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * The cached kernel info.\n *\n * @returns A promise that resolves to the kernel info.\n */\n get info() {\n return this._info.promise;\n }\n /**\n * The kernel spec.\n *\n * @returns A promise that resolves to the kernel spec.\n */\n get spec() {\n if (this._specPromise) {\n return this._specPromise;\n }\n this._specPromise = kernelspec_1.KernelSpecAPI.getSpecs(this.serverSettings).then(specs => {\n return specs.kernelspecs[this._name];\n });\n return this._specPromise;\n }\n /**\n * Clone the current kernel with a new clientId.\n */\n clone(options = {}) {\n return new KernelConnection({\n model: this.model,\n username: this.username,\n serverSettings: this.serverSettings,\n // handleComms defaults to false since that is safer\n handleComms: false,\n ...options\n });\n }\n /**\n * Dispose of the resources held by the kernel.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n this._updateConnectionStatus('disconnected');\n this._clearKernelState();\n this._pendingMessages = [];\n this._clearSocket();\n // Clear Lumino signals\n signaling_1.Signal.clearData(this);\n }\n /**\n * Send a shell message to the kernel.\n *\n * #### Notes\n * Send a message to the kernel's shell channel, yielding a future object\n * for accepting replies.\n *\n * If `expectReply` is given and `true`, the future is disposed when both a\n * shell reply and an idle status message are received. If `expectReply`\n * is not given or is `false`, the future is resolved when an idle status\n * message is received.\n * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.\n * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.\n *\n * All replies are validated as valid kernel messages.\n *\n * If the kernel status is `dead`, this will throw an error.\n */\n sendShellMessage(msg, expectReply = false, disposeOnDone = true) {\n return this._sendKernelShellControl(future_1.KernelShellFutureHandler, msg, expectReply, disposeOnDone);\n }\n /**\n * Send a control message to the kernel.\n *\n * #### Notes\n * Send a message to the kernel's control channel, yielding a future object\n * for accepting replies.\n *\n * If `expectReply` is given and `true`, the future is disposed when both a\n * control reply and an idle status message are received. If `expectReply`\n * is not given or is `false`, the future is resolved when an idle status\n * message is received.\n * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.\n * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.\n *\n * All replies are validated as valid kernel messages.\n *\n * If the kernel status is `dead`, this will throw an error.\n */\n sendControlMessage(msg, expectReply = false, disposeOnDone = true) {\n return this._sendKernelShellControl(future_1.KernelControlFutureHandler, msg, expectReply, disposeOnDone);\n }\n _sendKernelShellControl(ctor, msg, expectReply = false, disposeOnDone = true) {\n this._sendMessage(msg);\n this._anyMessage.emit({ msg, direction: 'send' });\n const future = new ctor(() => {\n const msgId = msg.header.msg_id;\n this._futures.delete(msgId);\n // Remove stored display id information.\n const displayIds = this._msgIdToDisplayIds.get(msgId);\n if (!displayIds) {\n return;\n }\n displayIds.forEach(displayId => {\n const msgIds = this._displayIdToParentIds.get(displayId);\n if (msgIds) {\n const idx = msgIds.indexOf(msgId);\n if (idx === -1) {\n return;\n }\n if (msgIds.length === 1) {\n this._displayIdToParentIds.delete(displayId);\n }\n else {\n msgIds.splice(idx, 1);\n this._displayIdToParentIds.set(displayId, msgIds);\n }\n }\n });\n this._msgIdToDisplayIds.delete(msgId);\n }, msg, expectReply, disposeOnDone, this);\n this._futures.set(msg.header.msg_id, future);\n return future;\n }\n /**\n * Send a message on the websocket.\n *\n * If queue is true, queue the message for later sending if we cannot send\n * now. Otherwise throw an error.\n *\n * #### Notes\n * As an exception to the queueing, if we are sending a kernel_info_request\n * message while we think the kernel is restarting, we send the message\n * immediately without queueing. This is so that we can trigger a message\n * back, which will then clear the kernel restarting state.\n */\n _sendMessage(msg, queue = true) {\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n // If we have a kernel_info_request and we are starting or restarting, send the\n // kernel_info_request immediately if we can, and if not throw an error so\n // we can retry later. On restarting we do this because we must get at least one message\n // from the kernel to reset the kernel session (thus clearing the restart\n // status sentinel).\n if ((this._kernelSession === STARTING_KERNEL_SESSION ||\n this._kernelSession === RESTARTING_KERNEL_SESSION) &&\n KernelMessage.isInfoRequestMsg(msg)) {\n if (this.connectionStatus === 'connected') {\n this._ws.send((0, serialize_1.serialize)(msg, this._ws.protocol));\n return;\n }\n else {\n throw new Error('Could not send message: status is not connected');\n }\n }\n // If there are pending messages, add to the queue so we keep messages in order\n if (queue && this._pendingMessages.length > 0) {\n this._pendingMessages.push(msg);\n return;\n }\n // Send if the ws allows it, otherwise queue the message.\n if (this.connectionStatus === 'connected' &&\n this._kernelSession !== RESTARTING_KERNEL_SESSION) {\n this._ws.send((0, serialize_1.serialize)(msg, this._ws.protocol));\n }\n else if (queue) {\n this._pendingMessages.push(msg);\n }\n else {\n throw new Error('Could not send message');\n }\n }\n /**\n * Interrupt a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * It is assumed that the API call does not mutate the kernel id or name.\n *\n * The promise will be rejected if the kernel status is `Dead` or if the\n * request fails or the response is invalid.\n */\n async interrupt() {\n this.hasPendingInput = false;\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n return restapi.interruptKernel(this.id, this.serverSettings);\n }\n /**\n * Request a kernel restart.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels)\n * and validates the response model.\n *\n * Any existing Future or Comm objects are cleared once the kernel has\n * actually be restarted.\n *\n * The promise is fulfilled on a valid server response (after the kernel restarts)\n * and rejected otherwise.\n *\n * It is assumed that the API call does not mutate the kernel id or name.\n *\n * The promise will be rejected if the request fails or the response is\n * invalid.\n */\n async restart() {\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n this._updateStatus('restarting');\n this._clearKernelState();\n this._kernelSession = RESTARTING_KERNEL_SESSION;\n await restapi.restartKernel(this.id, this.serverSettings);\n // Reconnect to the kernel to address cases where kernel ports\n // have changed during the restart.\n await this.reconnect();\n this.hasPendingInput = false;\n }\n /**\n * Reconnect to a kernel.\n *\n * #### Notes\n * This may try multiple times to reconnect to a kernel, and will sever any\n * existing connection.\n */\n reconnect() {\n this._errorIfDisposed();\n const result = new coreutils_2.PromiseDelegate();\n // Set up a listener for the connection status changing, which accepts or\n // rejects after the retries are done.\n const fulfill = (sender, status) => {\n if (status === 'connected') {\n result.resolve();\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n else if (status === 'disconnected') {\n result.reject(new Error('Kernel connection disconnected'));\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n };\n this.connectionStatusChanged.connect(fulfill, this);\n // Reset the reconnect limit so we start the connection attempts fresh\n this._reconnectAttempt = 0;\n // Start the reconnection process, which will also clear any existing\n // connection.\n this._reconnect();\n // Return the promise that should resolve on connection or reject if the\n // retries don't work.\n return result.promise;\n }\n /**\n * Shutdown a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * On a valid response, disposes this kernel connection.\n *\n * If the kernel is already `dead`, disposes this kernel connection without\n * a server request.\n */\n async shutdown() {\n if (this.status !== 'dead') {\n await restapi.shutdownKernel(this.id, this.serverSettings);\n }\n this.handleShutdown();\n }\n /**\n * Handles a kernel shutdown.\n *\n * #### Notes\n * This method should be called if we know from outside information that a\n * kernel is dead (for example, we cannot find the kernel model on the\n * server).\n */\n handleShutdown() {\n this._updateStatus('dead');\n this.dispose();\n }\n /**\n * Send a `kernel_info_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n *\n * Fulfills with the `kernel_info_response` content when the shell reply is\n * received and validated.\n */\n async requestKernelInfo() {\n const msg = KernelMessage.createMessage({\n msgType: 'kernel_info_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content: {}\n });\n let reply;\n try {\n reply = (await Private.handleShellMessage(this, msg));\n }\n catch (e) {\n // If we rejected because the future was disposed, ignore and return.\n if (this.isDisposed) {\n return;\n }\n else {\n throw e;\n }\n }\n this._errorIfDisposed();\n if (!reply) {\n return;\n }\n // Kernels sometimes do not include a status field on kernel_info_reply\n // messages, so set a default for now.\n // See https://github.com/jupyterlab/jupyterlab/issues/6760\n if (reply.content.status === undefined) {\n reply.content.status = 'ok';\n }\n if (reply.content.status !== 'ok') {\n this._info.reject('Kernel info reply errored');\n return reply;\n }\n this._info.resolve(reply.content);\n this._kernelSession = reply.header.session;\n return reply;\n }\n /**\n * Send a `complete_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).\n *\n * Fulfills with the `complete_reply` content when the shell reply is\n * received and validated.\n */\n requestComplete(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'complete_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send an `inspect_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).\n *\n * Fulfills with the `inspect_reply` content when the shell reply is\n * received and validated.\n */\n requestInspect(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'inspect_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content: content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send a `history_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * Fulfills with the `history_reply` content when the shell reply is\n * received and validated.\n */\n requestHistory(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'history_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send an `execute_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).\n *\n * Future `onReply` is called with the `execute_reply` content when the\n * shell reply is received and validated. The future will resolve when\n * this message is received and the `idle` iopub status is received.\n * The future will also be disposed at this point unless `disposeOnDone`\n * is specified and `false`, in which case it is up to the caller to dispose\n * of the future.\n *\n * **See also:** [[IExecuteReply]]\n */\n requestExecute(content, disposeOnDone = true, metadata) {\n const defaults = {\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: true,\n stop_on_error: false\n };\n const msg = KernelMessage.createMessage({\n msgType: 'execute_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content: { ...defaults, ...content },\n metadata\n });\n return this.sendShellMessage(msg, true, disposeOnDone);\n }\n /**\n * Send an experimental `debug_request` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\n requestDebug(content, disposeOnDone = true) {\n const msg = KernelMessage.createMessage({\n msgType: 'debug_request',\n channel: 'control',\n username: this._username,\n session: this._clientId,\n content\n });\n return this.sendControlMessage(msg, true, disposeOnDone);\n }\n /**\n * Send an `is_complete_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).\n *\n * Fulfills with the `is_complete_response` content when the shell reply is\n * received and validated.\n */\n requestIsComplete(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'is_complete_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send a `comm_info_request` message.\n *\n * #### Notes\n * Fulfills with the `comm_info_reply` content when the shell reply is\n * received and validated.\n */\n requestCommInfo(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'comm_info_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send an `input_reply` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).\n */\n sendInputReply(content, parent_header) {\n const msg = KernelMessage.createMessage({\n msgType: 'input_reply',\n channel: 'stdin',\n username: this._username,\n session: this._clientId,\n content\n });\n msg.parent_header = parent_header;\n this._sendMessage(msg);\n this._anyMessage.emit({ msg, direction: 'send' });\n this.hasPendingInput = false;\n }\n /**\n * Create a new comm.\n *\n * #### Notes\n * If a client-side comm already exists with the given commId, an error is thrown.\n * If the kernel does not handle comms, an error is thrown.\n */\n createComm(targetName, commId = coreutils_2.UUID.uuid4()) {\n if (!this.handleComms) {\n throw new Error('Comms are disabled on this kernel connection');\n }\n if (this._comms.has(commId)) {\n throw new Error('Comm is already created');\n }\n const comm = new comm_1.CommHandler(targetName, commId, this, () => {\n this._unregisterComm(commId);\n });\n this._comms.set(commId, comm);\n return comm;\n }\n /**\n * Check if a comm exists.\n */\n hasComm(commId) {\n return this._comms.has(commId);\n }\n /**\n * Register a comm target handler.\n *\n * @param targetName - The name of the comm target.\n *\n * @param callback - The callback invoked for a comm open message.\n *\n * @returns A disposable used to unregister the comm target.\n *\n * #### Notes\n * Only one comm target can be registered to a target name at a time, an\n * existing callback for the same target name will be overridden. A registered\n * comm target handler will take precedence over a comm which specifies a\n * `target_module`.\n *\n * If the callback returns a promise, kernel message processing will pause\n * until the returned promise is fulfilled.\n */\n registerCommTarget(targetName, callback) {\n if (!this.handleComms) {\n return;\n }\n this._targetRegistry[targetName] = callback;\n }\n /**\n * Remove a comm target handler.\n *\n * @param targetName - The name of the comm target to remove.\n *\n * @param callback - The callback to remove.\n *\n * #### Notes\n * The comm target is only removed if the callback argument matches.\n */\n removeCommTarget(targetName, callback) {\n if (!this.handleComms) {\n return;\n }\n if (!this.isDisposed && this._targetRegistry[targetName] === callback) {\n delete this._targetRegistry[targetName];\n }\n }\n /**\n * Register an IOPub message hook.\n *\n * @param msg_id - The parent_header message id the hook will intercept.\n *\n * @param hook - The callback invoked for the message.\n *\n * #### Notes\n * The IOPub hook system allows you to preempt the handlers for IOPub\n * messages that are responses to a given message id.\n *\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case all kernel message\n * processing pauses until the promise is fulfilled. If a hook return value\n * resolves to false, any later hooks will not run and the function will\n * return a promise resolving to false. If a hook throws an error, the error\n * is logged to the console and the next hook is run. If a hook is\n * registered during the hook processing, it will not run until the next\n * message. If a hook is removed during the hook processing, it will be\n * deactivated immediately.\n *\n * See also [[IFuture.registerMessageHook]].\n */\n registerMessageHook(msgId, hook) {\n var _a;\n const future = (_a = this._futures) === null || _a === void 0 ? void 0 : _a.get(msgId);\n if (future) {\n future.registerMessageHook(hook);\n }\n }\n /**\n * Remove an IOPub message hook.\n *\n * @param msg_id - The parent_header message id the hook intercepted.\n *\n * @param hook - The callback invoked for the message.\n *\n */\n removeMessageHook(msgId, hook) {\n var _a;\n const future = (_a = this._futures) === null || _a === void 0 ? void 0 : _a.get(msgId);\n if (future) {\n future.removeMessageHook(hook);\n }\n }\n /**\n * Remove the input guard, if any.\n */\n removeInputGuard() {\n this.hasPendingInput = false;\n }\n /**\n * Handle a message with a display id.\n *\n * @returns Whether the message was handled.\n */\n async _handleDisplayId(displayId, msg) {\n var _a, _b;\n const msgId = msg.parent_header.msg_id;\n let parentIds = this._displayIdToParentIds.get(displayId);\n if (parentIds) {\n // We've seen it before, update existing outputs with same display_id\n // by handling display_data as update_display_data.\n const updateMsg = {\n header: coreutils_2.JSONExt.deepCopy(msg.header),\n parent_header: coreutils_2.JSONExt.deepCopy(msg.parent_header),\n metadata: coreutils_2.JSONExt.deepCopy(msg.metadata),\n content: coreutils_2.JSONExt.deepCopy(msg.content),\n channel: msg.channel,\n buffers: msg.buffers ? msg.buffers.slice() : []\n };\n updateMsg.header.msg_type = 'update_display_data';\n await Promise.all(parentIds.map(async (parentId) => {\n const future = this._futures && this._futures.get(parentId);\n if (future) {\n await future.handleMsg(updateMsg);\n }\n }));\n }\n // We're done here if it's update_display.\n if (msg.header.msg_type === 'update_display_data') {\n // It's an update, don't proceed to the normal display.\n return true;\n }\n // Regular display_data with id, record it for future updating\n // in _displayIdToParentIds for future lookup.\n parentIds = (_a = this._displayIdToParentIds.get(displayId)) !== null && _a !== void 0 ? _a : [];\n if (parentIds.indexOf(msgId) === -1) {\n parentIds.push(msgId);\n }\n this._displayIdToParentIds.set(displayId, parentIds);\n // Add to our map of display ids for this message.\n const displayIds = (_b = this._msgIdToDisplayIds.get(msgId)) !== null && _b !== void 0 ? _b : [];\n if (displayIds.indexOf(msgId) === -1) {\n displayIds.push(msgId);\n }\n this._msgIdToDisplayIds.set(msgId, displayIds);\n // Let the message propagate to the intended recipient.\n return false;\n }\n /**\n * Forcefully clear the socket state.\n *\n * #### Notes\n * This will clear all socket state without calling any handlers and will\n * not update the connection status. If you call this method, you are\n * responsible for updating the connection status as needed and recreating\n * the socket if you plan to reconnect.\n */\n _clearSocket() {\n if (this._ws !== null) {\n // Clear the websocket event handlers and the socket itself.\n this._ws.onopen = this._noOp;\n this._ws.onclose = this._noOp;\n this._ws.onerror = this._noOp;\n this._ws.onmessage = this._noOp;\n this._ws.close();\n this._ws = null;\n }\n }\n /**\n * Handle status iopub messages from the kernel.\n */\n _updateStatus(status) {\n if (this._status === status || this._status === 'dead') {\n return;\n }\n this._status = status;\n Private.logKernelStatus(this);\n this._statusChanged.emit(status);\n if (status === 'dead') {\n this.dispose();\n }\n }\n /**\n * Send pending messages to the kernel.\n */\n _sendPending() {\n // We check to make sure we are still connected each time. For\n // example, if a websocket buffer overflows, it may close, so we should\n // stop sending messages.\n while (this.connectionStatus === 'connected' &&\n this._kernelSession !== RESTARTING_KERNEL_SESSION &&\n this._pendingMessages.length > 0) {\n this._sendMessage(this._pendingMessages[0], false);\n // We shift the message off the queue after the message is sent so that\n // if there is an exception, the message is still pending.\n this._pendingMessages.shift();\n }\n }\n /**\n * Clear the internal state.\n */\n _clearKernelState() {\n this._kernelSession = '';\n this._pendingMessages = [];\n this._futures.forEach(future => {\n future.dispose();\n });\n this._comms.forEach(comm => {\n comm.dispose();\n });\n this._msgChain = Promise.resolve();\n this._futures = new Map();\n this._comms = new Map();\n this._displayIdToParentIds.clear();\n this._msgIdToDisplayIds.clear();\n }\n /**\n * Check to make sure it is okay to proceed to handle a message.\n *\n * #### Notes\n * Because we handle messages asynchronously, before a message is handled the\n * kernel might be disposed or restarted (and have a different session id).\n * This function throws an error in each of these cases. This is meant to be\n * called at the start of an asynchronous message handler to cancel message\n * processing if the message no longer is valid.\n */\n _assertCurrentMessage(msg) {\n this._errorIfDisposed();\n if (msg.header.session !== this._kernelSession) {\n throw new Error(`Canceling handling of old message: ${msg.header.msg_type}`);\n }\n }\n /**\n * Handle a `comm_open` kernel message.\n */\n async _handleCommOpen(msg) {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = new comm_1.CommHandler(content.target_name, content.comm_id, this, () => {\n this._unregisterComm(content.comm_id);\n });\n this._comms.set(content.comm_id, comm);\n try {\n const target = await Private.loadObject(content.target_name, content.target_module, this._targetRegistry);\n await target(comm, msg);\n }\n catch (e) {\n // Close the comm asynchronously. We cannot block message processing on\n // kernel messages to wait for another kernel message.\n comm.close();\n console.error('Exception opening new comm');\n throw e;\n }\n }\n /**\n * Handle 'comm_close' kernel message.\n */\n async _handleCommClose(msg) {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = this._comms.get(content.comm_id);\n if (!comm) {\n console.error('Comm not found for comm id ' + content.comm_id);\n return;\n }\n this._unregisterComm(comm.commId);\n const onClose = comm.onClose;\n if (onClose) {\n // tslint:disable-next-line:await-promise\n await onClose(msg);\n }\n comm.dispose();\n }\n /**\n * Handle a 'comm_msg' kernel message.\n */\n async _handleCommMsg(msg) {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = this._comms.get(content.comm_id);\n if (!comm) {\n return;\n }\n const onMsg = comm.onMsg;\n if (onMsg) {\n // tslint:disable-next-line:await-promise\n await onMsg(msg);\n }\n }\n /**\n * Unregister a comm instance.\n */\n _unregisterComm(commId) {\n this._comms.delete(commId);\n }\n /**\n * Handle connection status changes.\n */\n _updateConnectionStatus(connectionStatus) {\n if (this._connectionStatus === connectionStatus) {\n return;\n }\n this._connectionStatus = connectionStatus;\n // If we are not 'connecting', reset any reconnection attempts.\n if (connectionStatus !== 'connecting') {\n this._reconnectAttempt = 0;\n clearTimeout(this._reconnectTimeout);\n }\n if (this.status !== 'dead') {\n if (connectionStatus === 'connected') {\n let restarting = this._kernelSession === RESTARTING_KERNEL_SESSION;\n // Send a kernel info request to make sure we send at least one\n // message to get kernel status back. Always request kernel info\n // first, to get kernel status back and ensure iopub is fully\n // established. If we are restarting, this message will skip the queue\n // and be sent immediately.\n let p = this.requestKernelInfo();\n // Send any pending messages after the kernelInfo resolves, or after a\n // timeout as a failsafe.\n let sendPendingCalled = false;\n let sendPendingOnce = () => {\n if (sendPendingCalled) {\n return;\n }\n sendPendingCalled = true;\n if (restarting && this._kernelSession === RESTARTING_KERNEL_SESSION) {\n // We were restarting and a message didn't arrive to set the\n // session, but we just assume the restart succeeded and send any\n // pending messages.\n // FIXME: it would be better to retry the kernel_info_request here\n this._kernelSession = '';\n }\n clearTimeout(timeoutHandle);\n if (this._pendingMessages.length > 0) {\n this._sendPending();\n }\n };\n void p.then(sendPendingOnce);\n // FIXME: if sent while zmq subscriptions are not established,\n // kernelInfo may not resolve, so use a timeout to ensure we don't hang forever.\n // It may be preferable to retry kernelInfo rather than give up after one timeout.\n let timeoutHandle = setTimeout(sendPendingOnce, KERNEL_INFO_TIMEOUT);\n }\n else {\n // If the connection is down, then we do not know what is happening\n // with the kernel, so set the status to unknown.\n this._updateStatus('unknown');\n }\n }\n // Notify others that the connection status changed.\n this._connectionStatusChanged.emit(connectionStatus);\n }\n async _handleMessage(msg) {\n var _a, _b;\n let handled = false;\n // Check to see if we have a display_id we need to reroute.\n if (msg.parent_header &&\n msg.channel === 'iopub' &&\n (KernelMessage.isDisplayDataMsg(msg) ||\n KernelMessage.isUpdateDisplayDataMsg(msg) ||\n KernelMessage.isExecuteResultMsg(msg))) {\n // display_data messages may re-route based on their display_id.\n const transient = ((_a = msg.content.transient) !== null && _a !== void 0 ? _a : {});\n const displayId = transient['display_id'];\n if (displayId) {\n handled = await this._handleDisplayId(displayId, msg);\n // The await above may make this message out of date, so check again.\n this._assertCurrentMessage(msg);\n }\n }\n if (!handled && msg.parent_header) {\n const parentHeader = msg.parent_header;\n const future = (_b = this._futures) === null || _b === void 0 ? void 0 : _b.get(parentHeader.msg_id);\n if (future) {\n await future.handleMsg(msg);\n this._assertCurrentMessage(msg);\n }\n else {\n // If the message was sent by us and was not iopub, it is orphaned.\n const owned = parentHeader.session === this.clientId;\n if (msg.channel !== 'iopub' && owned) {\n this._unhandledMessage.emit(msg);\n }\n }\n }\n if (msg.channel === 'iopub') {\n switch (msg.header.msg_type) {\n case 'status': {\n // Updating the status is synchronous, and we call no async user code\n const executionState = msg.content\n .execution_state;\n if (executionState === 'restarting') {\n // The kernel has been auto-restarted by the server. After\n // processing for this message is completely done, we want to\n // handle this restart, so we don't await, but instead schedule\n // the work as a microtask (i.e., in a promise resolution). We\n // schedule this here so that it comes before any microtasks that\n // might be scheduled in the status signal emission below.\n void Promise.resolve().then(async () => {\n this._updateStatus('autorestarting');\n this._clearKernelState();\n // We must reconnect since the kernel connection information may have\n // changed, and the server only refreshes its zmq connection when a new\n // websocket is opened.\n await this.reconnect();\n });\n }\n this._updateStatus(executionState);\n break;\n }\n case 'comm_open':\n if (this.handleComms) {\n await this._handleCommOpen(msg);\n }\n break;\n case 'comm_msg':\n if (this.handleComms) {\n await this._handleCommMsg(msg);\n }\n break;\n case 'comm_close':\n if (this.handleComms) {\n await this._handleCommClose(msg);\n }\n break;\n default:\n break;\n }\n // If the message was a status dead message, we might have disposed ourselves.\n if (!this.isDisposed) {\n this._assertCurrentMessage(msg);\n // the message wouldn't be emitted if we were disposed anyway.\n this._iopubMessage.emit(msg);\n }\n }\n }\n /**\n * Attempt a connection if we have not exhausted connection attempts.\n */\n _reconnect() {\n this._errorIfDisposed();\n // Clear any existing reconnection attempt\n clearTimeout(this._reconnectTimeout);\n // Update the connection status and schedule a possible reconnection.\n if (this._reconnectAttempt < this._reconnectLimit) {\n this._updateConnectionStatus('connecting');\n // The first reconnect attempt should happen immediately, and subsequent\n // attempts should pick a random number in a growing range so that we\n // don't overload the server with synchronized reconnection attempts\n // across multiple kernels.\n const timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));\n console.warn(`Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`);\n // Try reconnection with subprotocols if the server had supported them.\n // Otherwise, try reconnection without subprotocols.\n const useProtocols = this._selectedProtocol !== '' ? true : false;\n this._reconnectTimeout = setTimeout(this._createSocket, timeout, useProtocols);\n this._reconnectAttempt += 1;\n }\n else {\n this._updateConnectionStatus('disconnected');\n }\n // Clear the websocket event handlers and the socket itself.\n this._clearSocket();\n }\n /**\n * Utility function to throw an error if this instance is disposed.\n */\n _errorIfDisposed() {\n if (this.isDisposed) {\n throw new Error('Kernel connection is disposed');\n }\n }\n get hasPendingInput() {\n return this._hasPendingInput;\n }\n set hasPendingInput(value) {\n this._hasPendingInput = value;\n this._pendingInput.emit(value);\n }\n}\nexports.KernelConnection = KernelConnection;\n/**\n * A private namespace for the Kernel.\n */\nvar Private;\n(function (Private) {\n /**\n * Log the current kernel status.\n */\n function logKernelStatus(kernel) {\n switch (kernel.status) {\n case 'idle':\n case 'busy':\n case 'unknown':\n return;\n default:\n console.debug(`Kernel: ${kernel.status} (${kernel.id})`);\n break;\n }\n }\n Private.logKernelStatus = logKernelStatus;\n /**\n * Send a kernel message to the kernel and resolve the reply message.\n */\n async function handleShellMessage(kernel, msg) {\n const future = kernel.sendShellMessage(msg, true);\n return future.done;\n }\n Private.handleShellMessage = handleShellMessage;\n /**\n * Try to load an object from a module or a registry.\n *\n * Try to load an object from a module asynchronously if a module\n * is specified, otherwise tries to load an object from the global\n * registry, if the global registry is provided.\n *\n * #### Notes\n * Loading a module uses requirejs.\n */\n function loadObject(name, moduleName, registry) {\n return new Promise((resolve, reject) => {\n // Try loading the module using require.js\n if (moduleName) {\n if (typeof requirejs === 'undefined') {\n throw new Error('requirejs not found');\n }\n requirejs([moduleName], (mod) => {\n if (mod[name] === void 0) {\n const msg = `Object '${name}' not found in module '${moduleName}'`;\n reject(new Error(msg));\n }\n else {\n resolve(mod[name]);\n }\n }, reject);\n }\n else {\n if (registry === null || registry === void 0 ? void 0 : registry[name]) {\n resolve(registry[name]);\n }\n else {\n reject(new Error(`Object '${name}' not found in registry`));\n }\n }\n });\n }\n Private.loadObject = loadObject;\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n Private.getRandomIntInclusive = getRandomIntInclusive;\n})(Private || (Private = {}));\n//# sourceMappingURL=default.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelShellFutureHandler = exports.KernelControlFutureHandler = exports.KernelFutureHandler = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst disposable_1 = require(\"@lumino/disposable\");\nconst KernelMessage = __importStar(require(\"./messages\"));\n/**\n * Implementation of a kernel future.\n *\n * If a reply is expected, the Future is considered done when both a `reply`\n * message and an `idle` iopub status message have been received. Otherwise, it\n * is considered done when the `idle` status is received.\n *\n */\nclass KernelFutureHandler extends disposable_1.DisposableDelegate {\n /**\n * Construct a new KernelFutureHandler.\n */\n constructor(cb, msg, expectReply, disposeOnDone, kernel) {\n super(cb);\n this._status = 0;\n this._stdin = Private.noOp;\n this._iopub = Private.noOp;\n this._reply = Private.noOp;\n this._done = new coreutils_1.PromiseDelegate();\n this._hooks = new Private.HookList();\n this._disposeOnDone = true;\n this._msg = msg;\n if (!expectReply) {\n this._setFlag(Private.KernelFutureFlag.GotReply);\n }\n this._disposeOnDone = disposeOnDone;\n this._kernel = kernel;\n }\n /**\n * Get the original outgoing message.\n */\n get msg() {\n return this._msg;\n }\n /**\n * A promise that resolves when the future is done.\n */\n get done() {\n return this._done.promise;\n }\n /**\n * Get the reply handler.\n */\n get onReply() {\n return this._reply;\n }\n /**\n * Set the reply handler.\n */\n set onReply(cb) {\n this._reply = cb;\n }\n /**\n * Get the iopub handler.\n */\n get onIOPub() {\n return this._iopub;\n }\n /**\n * Set the iopub handler.\n */\n set onIOPub(cb) {\n this._iopub = cb;\n }\n /**\n * Get the stdin handler.\n */\n get onStdin() {\n return this._stdin;\n }\n /**\n * Set the stdin handler.\n */\n set onStdin(cb) {\n this._stdin = cb;\n }\n /**\n * Register hook for IOPub messages.\n *\n * @param hook - The callback invoked for an IOPub message.\n *\n * #### Notes\n * The IOPub hook system allows you to preempt the handlers for IOPub\n * messages handled by the future.\n *\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case all kernel message\n * processing pauses until the promise is fulfilled. If a hook return value\n * resolves to false, any later hooks will not run and the function will\n * return a promise resolving to false. If a hook throws an error, the error\n * is logged to the console and the next hook is run. If a hook is\n * registered during the hook processing, it will not run until the next\n * message. If a hook is removed during the hook processing, it will be\n * deactivated immediately.\n */\n registerMessageHook(hook) {\n if (this.isDisposed) {\n throw new Error('Kernel future is disposed');\n }\n this._hooks.add(hook);\n }\n /**\n * Remove a hook for IOPub messages.\n *\n * @param hook - The hook to remove.\n *\n * #### Notes\n * If a hook is removed during the hook processing, it will be deactivated immediately.\n */\n removeMessageHook(hook) {\n if (this.isDisposed) {\n return;\n }\n this._hooks.remove(hook);\n }\n /**\n * Send an `input_reply` message.\n */\n sendInputReply(content, parent_header) {\n this._kernel.sendInputReply(content, parent_header);\n }\n /**\n * Dispose and unregister the future.\n */\n dispose() {\n this._stdin = Private.noOp;\n this._iopub = Private.noOp;\n this._reply = Private.noOp;\n this._hooks = null;\n if (!this._testFlag(Private.KernelFutureFlag.IsDone)) {\n // TODO: Uncomment the following logging code, and check for any tests that trigger it.\n // let status = [];\n // if (!this._testFlag(Private.KernelFutureFlag.GotIdle)) {\n // status.push('idle');\n // }\n // if (!this._testFlag(Private.KernelFutureFlag.GotReply)) {\n // status.push('reply');\n // }\n // console.warn(\n // `*************** DISPOSED BEFORE DONE: K${this._kernel.id.slice(\n // 0,\n // 6\n // )} M${this._msg.header.msg_id.slice(0, 6)} missing ${status.join(' ')}`\n // );\n // Reject the `done` promise, but catch its error here in case no one else\n // is waiting for the promise to resolve. This prevents the error from\n // being displayed in the console, but does not prevent it from being\n // caught by a client who is waiting for it.\n this._done.promise.catch(() => {\n /* no-op */\n });\n this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`));\n }\n super.dispose();\n }\n /**\n * Handle an incoming kernel message.\n */\n async handleMsg(msg) {\n switch (msg.channel) {\n case 'control':\n case 'shell':\n if (msg.channel === this.msg.channel &&\n msg.parent_header.msg_id === this.msg.header.msg_id) {\n await this._handleReply(msg);\n }\n break;\n case 'stdin':\n await this._handleStdin(msg);\n break;\n case 'iopub':\n await this._handleIOPub(msg);\n break;\n default:\n break;\n }\n }\n async _handleReply(msg) {\n const reply = this._reply;\n if (reply) {\n // tslint:disable-next-line:await-promise\n await reply(msg);\n }\n this._replyMsg = msg;\n this._setFlag(Private.KernelFutureFlag.GotReply);\n if (this._testFlag(Private.KernelFutureFlag.GotIdle)) {\n this._handleDone();\n }\n }\n async _handleStdin(msg) {\n this._kernel.hasPendingInput = true;\n const stdin = this._stdin;\n if (stdin) {\n // tslint:disable-next-line:await-promise\n await stdin(msg);\n }\n }\n async _handleIOPub(msg) {\n const process = await this._hooks.process(msg);\n const iopub = this._iopub;\n if (process && iopub) {\n // tslint:disable-next-line:await-promise\n await iopub(msg);\n }\n if (KernelMessage.isStatusMsg(msg) &&\n msg.content.execution_state === 'idle') {\n this._setFlag(Private.KernelFutureFlag.GotIdle);\n if (this._testFlag(Private.KernelFutureFlag.GotReply)) {\n this._handleDone();\n }\n }\n }\n _handleDone() {\n if (this._testFlag(Private.KernelFutureFlag.IsDone)) {\n return;\n }\n this._setFlag(Private.KernelFutureFlag.IsDone);\n this._done.resolve(this._replyMsg);\n if (this._disposeOnDone) {\n this.dispose();\n }\n }\n /**\n * Test whether the given future flag is set.\n */\n _testFlag(flag) {\n // tslint:disable-next-line\n return (this._status & flag) !== 0;\n }\n /**\n * Set the given future flag.\n */\n _setFlag(flag) {\n // tslint:disable-next-line\n this._status |= flag;\n }\n}\nexports.KernelFutureHandler = KernelFutureHandler;\nclass KernelControlFutureHandler extends KernelFutureHandler {\n}\nexports.KernelControlFutureHandler = KernelControlFutureHandler;\nclass KernelShellFutureHandler extends KernelFutureHandler {\n}\nexports.KernelShellFutureHandler = KernelShellFutureHandler;\nvar Private;\n(function (Private) {\n /**\n * A no-op function.\n */\n Private.noOp = () => {\n /* no-op */\n };\n /**\n * Defer a computation.\n *\n * #### NOTES\n * We can't just use requestAnimationFrame since it is not available in node.\n * This implementation is from Phosphor:\n * https://github.com/phosphorjs/phosphor/blob/e88e4321289bb1198f3098e7bda40736501f2ed8/tests/test-messaging/src/index.spec.ts#L63\n */\n const defer = (() => {\n const ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n class HookList {\n constructor() {\n this._hooks = [];\n }\n /**\n * Register a hook.\n *\n * @param hook - The callback to register.\n */\n add(hook) {\n this.remove(hook);\n this._hooks.push(hook);\n }\n /**\n * Remove a hook, if it exists in the hook list.\n *\n * @param hook - The callback to remove.\n */\n remove(hook) {\n const index = this._hooks.indexOf(hook);\n if (index >= 0) {\n this._hooks[index] = null;\n this._scheduleCompact();\n }\n }\n /**\n * Process a message through the hooks.\n *\n * @returns a promise resolving to false if any hook resolved as false,\n * otherwise true\n *\n * #### Notes\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case processing pauses until\n * the promise is fulfilled. If a hook return value resolves to false, any\n * later hooks will not run and the function will return a promise resolving\n * to false. If a hook throws an error, the error is logged to the console\n * and the next hook is run. If a hook is registered during the hook\n * processing, it will not run until the next message. If a hook is removed\n * during the hook processing, it will be deactivated immediately.\n */\n async process(msg) {\n // Wait until we can start a new process run.\n await this._processing;\n // Start the next process run.\n const processing = new coreutils_1.PromiseDelegate();\n this._processing = processing.promise;\n let continueHandling;\n // Call the end hook (most recently-added) first. Starting at the end also\n // guarantees that hooks added during the processing will not be run in\n // this process run.\n for (let i = this._hooks.length - 1; i >= 0; i--) {\n const hook = this._hooks[i];\n // If the hook has been removed, continue to the next one.\n if (hook === null) {\n continue;\n }\n // Execute the hook and log any errors.\n try {\n // tslint:disable-next-line:await-promise\n continueHandling = await hook(msg);\n }\n catch (err) {\n continueHandling = true;\n console.error(err);\n }\n // If the hook resolved to false, stop processing and return.\n if (continueHandling === false) {\n processing.resolve(undefined);\n return false;\n }\n }\n // All hooks returned true (or errored out), so return true.\n processing.resolve(undefined);\n return true;\n }\n /**\n * Schedule a cleanup of the list, removing any hooks that have been nulled out.\n */\n _scheduleCompact() {\n if (!this._compactScheduled) {\n this._compactScheduled = true;\n // Schedule a compaction in between processing runs. We do the\n // scheduling in an animation frame to rate-limit our compactions. If we\n // need to compact more frequently, we can change this to directly\n // schedule the compaction.\n defer(() => {\n this._processing = this._processing.then(() => {\n this._compactScheduled = false;\n this._compact();\n });\n });\n }\n }\n /**\n * Compact the list, removing any nulls.\n */\n _compact() {\n let numNulls = 0;\n for (let i = 0, len = this._hooks.length; i < len; i++) {\n const hook = this._hooks[i];\n if (this._hooks[i] === null) {\n numNulls++;\n }\n else {\n this._hooks[i - numNulls] = hook;\n }\n }\n this._hooks.length -= numNulls;\n }\n }\n Private.HookList = HookList;\n /**\n * Bit flags for the kernel future state.\n */\n let KernelFutureFlag;\n (function (KernelFutureFlag) {\n KernelFutureFlag[KernelFutureFlag[\"GotReply\"] = 1] = \"GotReply\";\n KernelFutureFlag[KernelFutureFlag[\"GotIdle\"] = 2] = \"GotIdle\";\n KernelFutureFlag[KernelFutureFlag[\"IsDone\"] = 4] = \"IsDone\";\n KernelFutureFlag[KernelFutureFlag[\"DisposeOnDone\"] = 8] = \"DisposeOnDone\";\n })(KernelFutureFlag = Private.KernelFutureFlag || (Private.KernelFutureFlag = {}));\n})(Private || (Private = {}));\n//# sourceMappingURL=future.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelConnection = exports.KernelAPI = exports.KernelMessage = exports.Kernel = void 0;\n// Namespace some of our modules for convenience and backwards compatibility.\nconst Kernel = __importStar(require(\"./kernel\"));\nexports.Kernel = Kernel;\nconst KernelMessage = __importStar(require(\"./messages\"));\nexports.KernelMessage = KernelMessage;\nconst KernelAPI = __importStar(require(\"./restapi\"));\nexports.KernelAPI = KernelAPI;\nconst default_1 = require(\"./default\");\nObject.defineProperty(exports, \"KernelConnection\", { enumerable: true, get: function () { return default_1.KernelConnection; } });\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=kernel.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelManager = void 0;\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst basemanager_1 = require(\"../basemanager\");\nconst restapi_1 = require(\"./restapi\");\nconst default_1 = require(\"./default\");\n/**\n * An implementation of a kernel manager.\n */\nclass KernelManager extends basemanager_1.BaseManager {\n /**\n * Construct a new kernel manager.\n *\n * @param options - The default options for kernel.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n this._kernelConnections = new Set();\n this._models = new Map();\n this._runningChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // Start model and specs polling with exponential backoff.\n this._pollModels = new polling_1.Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:KernelManager#models`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n this._isReady = true;\n })();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * A signal emitted when the running kernels change.\n */\n get runningChanged() {\n return this._runningChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._models.clear();\n this._kernelConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n /**\n * Connect to an existing kernel.\n *\n * @returns The new kernel connection.\n *\n * #### Notes\n * This will use the manager's server settings and ignore any server\n * settings passed in the options.\n */\n connectTo(options) {\n var _a;\n const { id } = options.model;\n let handleComms = (_a = options.handleComms) !== null && _a !== void 0 ? _a : true;\n // By default, handle comms only if no other kernel connection is.\n if (options.handleComms === undefined) {\n for (const kc of this._kernelConnections) {\n if (kc.id === id && kc.handleComms) {\n handleComms = false;\n break;\n }\n }\n }\n const kernelConnection = new default_1.KernelConnection({\n handleComms,\n ...options,\n serverSettings: this.serverSettings\n });\n this._onStarted(kernelConnection);\n if (!this._models.has(id)) {\n // We trust the user to connect to an existing kernel, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return kernelConnection;\n }\n /**\n * Create an iterator over the most recent running kernels.\n *\n * @returns A new iterator over the running kernels.\n */\n running() {\n return this._models.values();\n }\n /**\n * Force a refresh of the running kernels.\n *\n * @returns A promise that resolves when the running list has been refreshed.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n async refreshRunning() {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n /**\n * Start a new kernel.\n *\n * @param createOptions - The kernel creation options\n *\n * @param connectOptions - The kernel connection options\n *\n * @returns A promise that resolves with the kernel connection.\n *\n * #### Notes\n * The manager `serverSettings` will be always be used.\n */\n async startNew(createOptions = {}, connectOptions = {}) {\n const model = await (0, restapi_1.startNew)(createOptions, this.serverSettings);\n return this.connectTo({\n ...connectOptions,\n model\n });\n }\n /**\n * Shut down a kernel by id.\n *\n * @param id - The id of the target kernel.\n *\n * @returns A promise that resolves when the operation is complete.\n */\n async shutdown(id) {\n await (0, restapi_1.shutdownKernel)(id, this.serverSettings);\n await this.refreshRunning();\n }\n /**\n * Shut down all kernels.\n *\n * @returns A promise that resolves when all of the kernels are shut down.\n */\n async shutdownAll() {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n // Shut down all models.\n await Promise.all([...this._models.keys()].map(id => (0, restapi_1.shutdownKernel)(id, this.serverSettings)));\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n /**\n * Find a kernel by id.\n *\n * @param id - The id of the target kernel.\n *\n * @returns A promise that resolves with the kernel's model.\n */\n async findById(id) {\n if (this._models.has(id)) {\n return this._models.get(id);\n }\n await this.refreshRunning();\n return this._models.get(id);\n }\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n async requestRunning() {\n var _a, _b;\n let models;\n try {\n models = await (0, restapi_1.listRunning)(this.serverSettings);\n }\n catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof __1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n if (this.isDisposed) {\n return;\n }\n if (this._models.size === models.length &&\n models.every(model => {\n const existing = this._models.get(model.id);\n if (!existing) {\n return false;\n }\n return (existing.connections === model.connections &&\n existing.execution_state === model.execution_state &&\n existing.last_activity === model.last_activity &&\n existing.name === model.name &&\n existing.reason === model.reason &&\n existing.traceback === model.traceback);\n })) {\n // Identical models list (presuming models does not contain duplicate\n // ids), so just return\n return;\n }\n this._models = new Map(models.map(x => [x.id, x]));\n // For any kernel connection to a kernel that doesn't exist, notify it of\n // the shutdown.\n this._kernelConnections.forEach(kc => {\n if (!this._models.has(kc.id)) {\n kc.handleShutdown();\n }\n });\n this._runningChanged.emit(models);\n }\n /**\n * Handle a kernel starting.\n */\n _onStarted(kernelConnection) {\n this._kernelConnections.add(kernelConnection);\n kernelConnection.statusChanged.connect(this._onStatusChanged, this);\n kernelConnection.disposed.connect(this._onDisposed, this);\n }\n _onDisposed(kernelConnection) {\n this._kernelConnections.delete(kernelConnection);\n // A dispose emission could mean the server session is deleted, or that\n // the kernel JS object is disposed and the kernel still exists on the\n // server, so we refresh from the server to make sure we reflect the\n // server state.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n _onStatusChanged(kernelConnection, status) {\n if (status === 'dead') {\n // We asynchronously update our list of kernels, which asynchronously\n // will dispose them. We do not want to immediately dispose them because\n // there may be other signal handlers that want to be called.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n }\n}\nexports.KernelManager = KernelManager;\n/**\n * The namespace for `KernelManager` class statics.\n */\n(function (KernelManager) {\n /**\n * A no-op kernel manager to be used when starting kernels.\n */\n class NoopManager extends KernelManager {\n constructor() {\n super(...arguments);\n this._readyPromise = new Promise(() => {\n /* no-op */\n });\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return false;\n }\n /**\n * Used for testing.\n */\n get parentReady() {\n return super.ready;\n }\n /**\n * Start a new kernel - throws an error since it is not supported.\n */\n async startNew(createOptions = {}, connectOptions = {}) {\n return Promise.reject(new Error('Not implemented in no-op Kernel Manager'));\n }\n /**\n * Connect to an existing kernel - throws an error since it is not supported.\n */\n connectTo(options) {\n throw new Error('Not implemented in no-op Kernel Manager');\n }\n /**\n * Shut down a kernel by id - throws an error since it is not supported.\n */\n async shutdown(id) {\n return Promise.reject(new Error('Not implemented in no-op Kernel Manager'));\n }\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready() {\n return this.parentReady.then(() => this._readyPromise);\n }\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n async requestRunning() {\n return Promise.resolve();\n }\n }\n KernelManager.NoopManager = NoopManager;\n})(KernelManager = exports.KernelManager || (exports.KernelManager = {}));\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.supportedKernelWebSocketProtocols = exports.isInputReplyMsg = exports.isInputRequestMsg = exports.isDebugReplyMsg = exports.isDebugRequestMsg = exports.isExecuteReplyMsg = exports.isInfoRequestMsg = exports.isCommMsgMsg = exports.isCommCloseMsg = exports.isCommOpenMsg = exports.isDebugEventMsg = exports.isClearOutputMsg = exports.isStatusMsg = exports.isErrorMsg = exports.isExecuteResultMsg = exports.isExecuteInputMsg = exports.isUpdateDisplayDataMsg = exports.isDisplayDataMsg = exports.isStreamMsg = exports.createMessage = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nfunction createMessage(options) {\n var _a, _b, _c, _d, _e;\n return {\n buffers: (_a = options.buffers) !== null && _a !== void 0 ? _a : [],\n channel: options.channel,\n content: options.content,\n header: {\n date: new Date().toISOString(),\n msg_id: (_b = options.msgId) !== null && _b !== void 0 ? _b : coreutils_1.UUID.uuid4(),\n msg_type: options.msgType,\n session: options.session,\n username: (_c = options.username) !== null && _c !== void 0 ? _c : '',\n version: '5.2'\n },\n metadata: (_d = options.metadata) !== null && _d !== void 0 ? _d : {},\n parent_header: (_e = options.parentHeader) !== null && _e !== void 0 ? _e : {}\n };\n}\nexports.createMessage = createMessage;\n/**\n * Test whether a kernel message is a `'stream'` message.\n */\nfunction isStreamMsg(msg) {\n return msg.header.msg_type === 'stream';\n}\nexports.isStreamMsg = isStreamMsg;\n/**\n * Test whether a kernel message is an `'display_data'` message.\n */\nfunction isDisplayDataMsg(msg) {\n return msg.header.msg_type === 'display_data';\n}\nexports.isDisplayDataMsg = isDisplayDataMsg;\n/**\n * Test whether a kernel message is an `'update_display_data'` message.\n */\nfunction isUpdateDisplayDataMsg(msg) {\n return msg.header.msg_type === 'update_display_data';\n}\nexports.isUpdateDisplayDataMsg = isUpdateDisplayDataMsg;\n/**\n * Test whether a kernel message is an `'execute_input'` message.\n */\nfunction isExecuteInputMsg(msg) {\n return msg.header.msg_type === 'execute_input';\n}\nexports.isExecuteInputMsg = isExecuteInputMsg;\n/**\n * Test whether a kernel message is an `'execute_result'` message.\n */\nfunction isExecuteResultMsg(msg) {\n return msg.header.msg_type === 'execute_result';\n}\nexports.isExecuteResultMsg = isExecuteResultMsg;\n/**\n * Test whether a kernel message is an `'error'` message.\n */\nfunction isErrorMsg(msg) {\n return msg.header.msg_type === 'error';\n}\nexports.isErrorMsg = isErrorMsg;\n/**\n * Test whether a kernel message is a `'status'` message.\n */\nfunction isStatusMsg(msg) {\n return msg.header.msg_type === 'status';\n}\nexports.isStatusMsg = isStatusMsg;\n/**\n * Test whether a kernel message is a `'clear_output'` message.\n */\nfunction isClearOutputMsg(msg) {\n return msg.header.msg_type === 'clear_output';\n}\nexports.isClearOutputMsg = isClearOutputMsg;\n/**\n * Test whether a kernel message is an experimental `'debug_event'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nfunction isDebugEventMsg(msg) {\n return msg.header.msg_type === 'debug_event';\n}\nexports.isDebugEventMsg = isDebugEventMsg;\n/**\n * Test whether a kernel message is a `'comm_open'` message.\n */\nfunction isCommOpenMsg(msg) {\n return msg.header.msg_type === 'comm_open';\n}\nexports.isCommOpenMsg = isCommOpenMsg;\n/**\n * Test whether a kernel message is a `'comm_close'` message.\n */\nfunction isCommCloseMsg(msg) {\n return msg.header.msg_type === 'comm_close';\n}\nexports.isCommCloseMsg = isCommCloseMsg;\n/**\n * Test whether a kernel message is a `'comm_msg'` message.\n */\nfunction isCommMsgMsg(msg) {\n return msg.header.msg_type === 'comm_msg';\n}\nexports.isCommMsgMsg = isCommMsgMsg;\n/**\n * Test whether a kernel message is a `'kernel_info_request'` message.\n */\nfunction isInfoRequestMsg(msg) {\n return msg.header.msg_type === 'kernel_info_request';\n}\nexports.isInfoRequestMsg = isInfoRequestMsg;\n/**\n * Test whether a kernel message is an `'execute_reply'` message.\n */\nfunction isExecuteReplyMsg(msg) {\n return msg.header.msg_type === 'execute_reply';\n}\nexports.isExecuteReplyMsg = isExecuteReplyMsg;\n/**\n * Test whether a kernel message is an experimental `'debug_request'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nfunction isDebugRequestMsg(msg) {\n return msg.header.msg_type === 'debug_request';\n}\nexports.isDebugRequestMsg = isDebugRequestMsg;\n/**\n * Test whether a kernel message is an experimental `'debug_reply'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nfunction isDebugReplyMsg(msg) {\n return msg.header.msg_type === 'debug_reply';\n}\nexports.isDebugReplyMsg = isDebugReplyMsg;\n/**\n * Test whether a kernel message is an `'input_request'` message.\n */\nfunction isInputRequestMsg(msg) {\n return msg.header.msg_type === 'input_request';\n}\nexports.isInputRequestMsg = isInputRequestMsg;\n/**\n * Test whether a kernel message is an `'input_reply'` message.\n */\nfunction isInputReplyMsg(msg) {\n return msg.header.msg_type === 'input_reply';\n}\nexports.isInputReplyMsg = isInputReplyMsg;\n// ///////////////////////////////////////////////\n// Message (de)serialization\n// ///////////////////////////////////////////////\n/**\n * The list of supported kernel wire protocols over websocket.\n */\nvar supportedKernelWebSocketProtocols;\n(function (supportedKernelWebSocketProtocols) {\n supportedKernelWebSocketProtocols[\"v1KernelWebsocketJupyterOrg\"] = \"v1.kernel.websocket.jupyter.org\";\n})(supportedKernelWebSocketProtocols = exports.supportedKernelWebSocketProtocols || (exports.supportedKernelWebSocketProtocols = {}));\n//# sourceMappingURL=messages.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getKernelModel = exports.shutdownKernel = exports.interruptKernel = exports.restartKernel = exports.startNew = exports.listRunning = exports.KERNEL_SERVICE_URL = void 0;\nconst serverconnection_1 = require(\"../serverconnection\");\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst validate_1 = require(\"./validate\");\n/**\n * The url for the kernel service.\n */\nexports.KERNEL_SERVICE_URL = 'api/kernels';\n/**\n * Fetch the running kernels.\n *\n * @param settings - The optional server settings.\n *\n * @returns A promise that resolves with the list of running kernels.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModels)(data);\n return data;\n}\nexports.listRunning = listRunning;\n/**\n * Start a new kernel.\n *\n * @param options - The options used to create the kernel.\n *\n * @returns A promise that resolves with a kernel connection object.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function startNew(options = {}, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify(options)\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.startNew = startNew;\n/**\n * Restart a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response (and thus after a restart) and rejected otherwise.\n */\nasync function restartKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id), 'restart');\n const init = { method: 'POST' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModel)(data);\n}\nexports.restartKernel = restartKernel;\n/**\n * Interrupt a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function interruptKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id), 'interrupt');\n const init = { method: 'POST' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.interruptKernel = interruptKernel;\n/**\n * Shut down a kernel.\n *\n * @param id - The id of the running kernel.\n *\n * @param settings - The server settings for the request.\n *\n * @returns A promise that resolves when the kernel is shut down.\n *\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function shutdownKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id));\n const init = { method: 'DELETE' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const msg = `The kernel \"${id}\" does not exist on the server`;\n console.warn(msg);\n }\n else if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.shutdownKernel = shutdownKernel;\n/**\n * Get a full kernel model from the server by kernel id string.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function getKernelModel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id));\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status === 404) {\n return undefined;\n }\n else if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.getKernelModel = getKernelModel;\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deserialize = exports.serialize = void 0;\nconst KernelMessage = __importStar(require(\"./messages\"));\n/**\n * Serialize a kernel message for transport.\n */\nfunction serialize(msg, protocol = '') {\n switch (protocol) {\n case KernelMessage.supportedKernelWebSocketProtocols\n .v1KernelWebsocketJupyterOrg:\n return Private.serializeV1KernelWebsocketJupyterOrg(msg);\n default:\n return Private.serializeDefault(msg);\n }\n}\nexports.serialize = serialize;\n/**\n * Deserialize and return the unpacked message.\n */\nfunction deserialize(data, protocol = '') {\n switch (protocol) {\n case KernelMessage.supportedKernelWebSocketProtocols\n .v1KernelWebsocketJupyterOrg:\n return Private.deserializeV1KernelWebsocketJupyterOrg(data);\n default:\n return Private.deserializeDefault(data);\n }\n}\nexports.deserialize = deserialize;\nvar Private;\n(function (Private) {\n /**\n * Deserialize and return the unpacked message.\n * Protocol `v1.kernel.websocket.jupyter.org`\n */\n function deserializeV1KernelWebsocketJupyterOrg(binMsg) {\n let msg;\n const data = new DataView(binMsg);\n const offsetNumber = Number(data.getBigUint64(0, true /* littleEndian */));\n let offsets = [];\n for (let i = 0; i < offsetNumber; i++) {\n // WARNING: we cast our 64-bit unsigned int to a number!\n // so offsets cannot index up to 2**64 bytes\n offsets.push(Number(data.getBigUint64(8 * (i + 1), true /* littleEndian */)));\n }\n const decoder = new TextDecoder('utf8');\n const channel = decoder.decode(binMsg.slice(offsets[0], offsets[1]));\n const header = JSON.parse(decoder.decode(binMsg.slice(offsets[1], offsets[2])));\n const parent_header = JSON.parse(decoder.decode(binMsg.slice(offsets[2], offsets[3])));\n const metadata = JSON.parse(decoder.decode(binMsg.slice(offsets[3], offsets[4])));\n const content = JSON.parse(decoder.decode(binMsg.slice(offsets[4], offsets[5])));\n let buffers = [];\n for (let i = 5; i < offsets.length - 1; i++) {\n buffers.push(new DataView(binMsg.slice(offsets[i], offsets[i + 1])));\n }\n msg = {\n channel,\n header,\n parent_header,\n metadata,\n content,\n buffers\n };\n return msg;\n }\n Private.deserializeV1KernelWebsocketJupyterOrg = deserializeV1KernelWebsocketJupyterOrg;\n /**\n * Serialize a kernel message for transport.\n * Protocol `v1.kernel.websocket.jupyter.org`\n */\n function serializeV1KernelWebsocketJupyterOrg(msg) {\n const header = JSON.stringify(msg.header);\n const parentHeader = msg.parent_header == null ? '{}' : JSON.stringify(msg.parent_header);\n const metadata = JSON.stringify(msg.metadata);\n const content = JSON.stringify(msg.content);\n const buffers = msg.buffers !== undefined ? msg.buffers : [];\n const offsetNumber = 1 + 4 + buffers.length + 1;\n let offsets = [];\n offsets.push(8 * (1 + offsetNumber));\n offsets.push(msg.channel.length + offsets[offsets.length - 1]);\n const encoder = new TextEncoder();\n const channelEncoded = encoder.encode(msg.channel);\n const headerEncoded = encoder.encode(header);\n const parentHeaderEncoded = encoder.encode(parentHeader);\n const metadataEncoded = encoder.encode(metadata);\n const contentEncoded = encoder.encode(content);\n const binMsgNoBuff = new Uint8Array(channelEncoded.length +\n headerEncoded.length +\n parentHeaderEncoded.length +\n metadataEncoded.length +\n contentEncoded.length);\n binMsgNoBuff.set(channelEncoded);\n binMsgNoBuff.set(headerEncoded, channelEncoded.length);\n binMsgNoBuff.set(parentHeaderEncoded, channelEncoded.length + headerEncoded.length);\n binMsgNoBuff.set(metadataEncoded, channelEncoded.length + headerEncoded.length + parentHeaderEncoded.length);\n binMsgNoBuff.set(contentEncoded, channelEncoded.length +\n headerEncoded.length +\n parentHeaderEncoded.length +\n metadataEncoded.length);\n for (let length of [\n headerEncoded.length,\n parentHeaderEncoded.length,\n metadataEncoded.length,\n contentEncoded.length\n ]) {\n offsets.push(length + offsets[offsets.length - 1]);\n }\n let buffersByteLength = 0;\n for (let buffer of buffers) {\n let length = buffer.byteLength;\n offsets.push(length + offsets[offsets.length - 1]);\n buffersByteLength += length;\n }\n const binMsg = new Uint8Array(8 * (1 + offsetNumber) + binMsgNoBuff.byteLength + buffersByteLength);\n const word = new ArrayBuffer(8);\n const data = new DataView(word);\n data.setBigUint64(0, BigInt(offsetNumber), true /* littleEndian */);\n binMsg.set(new Uint8Array(word), 0);\n for (let i = 0; i < offsets.length; i++) {\n data.setBigUint64(0, BigInt(offsets[i]), true /* littleEndian */);\n binMsg.set(new Uint8Array(word), 8 * (i + 1));\n }\n binMsg.set(binMsgNoBuff, offsets[0]);\n for (let i = 0; i < buffers.length; i++) {\n const buffer = buffers[i];\n binMsg.set(new Uint8Array(ArrayBuffer.isView(buffer) ? buffer.buffer : buffer), offsets[5 + i]);\n }\n return binMsg.buffer;\n }\n Private.serializeV1KernelWebsocketJupyterOrg = serializeV1KernelWebsocketJupyterOrg;\n /**\n * Deserialize and return the unpacked message.\n * Default protocol\n *\n * #### Notes\n * Handles JSON blob strings and binary messages.\n */\n function deserializeDefault(data) {\n let value;\n if (typeof data === 'string') {\n value = JSON.parse(data);\n }\n else {\n value = deserializeBinary(data);\n }\n return value;\n }\n Private.deserializeDefault = deserializeDefault;\n /**\n * Serialize a kernel message for transport.\n * Default protocol\n *\n * #### Notes\n * If there is binary content, an `ArrayBuffer` is returned,\n * otherwise the message is converted to a JSON string.\n */\n function serializeDefault(msg) {\n var _a;\n let value;\n if ((_a = msg.buffers) === null || _a === void 0 ? void 0 : _a.length) {\n value = serializeBinary(msg);\n }\n else {\n value = JSON.stringify(msg);\n }\n return value;\n }\n Private.serializeDefault = serializeDefault;\n /**\n * Deserialize a binary message to a Kernel Message.\n */\n function deserializeBinary(buf) {\n const data = new DataView(buf);\n // read the header: 1 + nbufs 32b integers\n const nbufs = data.getUint32(0);\n const offsets = [];\n if (nbufs < 2) {\n throw new Error('Invalid incoming Kernel Message');\n }\n for (let i = 1; i <= nbufs; i++) {\n offsets.push(data.getUint32(i * 4));\n }\n const jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1]));\n const msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes));\n // the remaining chunks are stored as DataViews in msg.buffers\n msg.buffers = [];\n for (let i = 1; i < nbufs; i++) {\n const start = offsets[i];\n const stop = offsets[i + 1] || buf.byteLength;\n msg.buffers.push(new DataView(buf.slice(start, stop)));\n }\n return msg;\n }\n /**\n * Implement the binary serialization protocol.\n *\n * Serialize Kernel message to ArrayBuffer.\n */\n function serializeBinary(msg) {\n const offsets = [];\n const buffers = [];\n const encoder = new TextEncoder();\n let origBuffers = [];\n if (msg.buffers !== undefined) {\n origBuffers = msg.buffers;\n delete msg['buffers'];\n }\n const jsonUtf8 = encoder.encode(JSON.stringify(msg));\n buffers.push(jsonUtf8.buffer);\n for (let i = 0; i < origBuffers.length; i++) {\n // msg.buffers elements could be either views or ArrayBuffers\n // buffers elements are ArrayBuffers\n const b = origBuffers[i];\n buffers.push(ArrayBuffer.isView(b) ? b.buffer : b);\n }\n const nbufs = buffers.length;\n offsets.push(4 * (nbufs + 1));\n for (let i = 0; i + 1 < buffers.length; i++) {\n offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength);\n }\n const msgBuf = new Uint8Array(offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength);\n // use DataView.setUint32 for network byte-order\n const view = new DataView(msgBuf.buffer);\n // write nbufs to first 4 bytes\n view.setUint32(0, nbufs);\n // write offsets to next 4 * nbufs bytes\n for (let i = 0; i < offsets.length; i++) {\n view.setUint32(4 * (i + 1), offsets[i]);\n }\n // write all the buffers at their respective offsets\n for (let i = 0; i < buffers.length; i++) {\n msgBuf.set(new Uint8Array(buffers[i]), offsets[i]);\n }\n return msgBuf.buffer;\n }\n})(Private || (Private = {}));\n//# sourceMappingURL=serialize.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateModels = exports.validateModel = exports.validateMessage = void 0;\nconst validate_1 = require(\"../validate\");\n/**\n * Required fields for `IKernelHeader`.\n */\nconst HEADER_FIELDS = ['username', 'version', 'session', 'msg_id', 'msg_type'];\n/**\n * Required fields and types for contents of various types of `kernel.IMessage`\n * messages on the iopub channel.\n */\nconst IOPUB_CONTENT_FIELDS = {\n stream: { name: 'string', text: 'string' },\n display_data: { data: 'object', metadata: 'object' },\n execute_input: { code: 'string', execution_count: 'number' },\n execute_result: {\n execution_count: 'number',\n data: 'object',\n metadata: 'object'\n },\n error: { ename: 'string', evalue: 'string', traceback: 'object' },\n status: {\n execution_state: [\n 'string',\n ['starting', 'idle', 'busy', 'restarting', 'dead']\n ]\n },\n clear_output: { wait: 'boolean' },\n comm_open: { comm_id: 'string', target_name: 'string', data: 'object' },\n comm_msg: { comm_id: 'string', data: 'object' },\n comm_close: { comm_id: 'string' },\n shutdown_reply: { restart: 'boolean' } // Emitted by the IPython kernel.\n};\n/**\n * Validate the header of a kernel message.\n */\nfunction validateHeader(header) {\n for (let i = 0; i < HEADER_FIELDS.length; i++) {\n (0, validate_1.validateProperty)(header, HEADER_FIELDS[i], 'string');\n }\n}\n/**\n * Validate a kernel message object.\n */\nfunction validateMessage(msg) {\n (0, validate_1.validateProperty)(msg, 'metadata', 'object');\n (0, validate_1.validateProperty)(msg, 'content', 'object');\n (0, validate_1.validateProperty)(msg, 'channel', 'string');\n validateHeader(msg.header);\n if (msg.channel === 'iopub') {\n validateIOPubContent(msg);\n }\n}\nexports.validateMessage = validateMessage;\n/**\n * Validate content an kernel message on the iopub channel.\n */\nfunction validateIOPubContent(msg) {\n if (msg.channel === 'iopub') {\n const fields = IOPUB_CONTENT_FIELDS[msg.header.msg_type];\n // Check for unknown message type.\n if (fields === undefined) {\n return;\n }\n const names = Object.keys(fields);\n const content = msg.content;\n for (let i = 0; i < names.length; i++) {\n let args = fields[names[i]];\n if (!Array.isArray(args)) {\n args = [args];\n }\n (0, validate_1.validateProperty)(content, names[i], ...args);\n }\n }\n}\n/**\n * Validate a `Kernel.IModel` object.\n */\nfunction validateModel(model) {\n (0, validate_1.validateProperty)(model, 'name', 'string');\n (0, validate_1.validateProperty)(model, 'id', 'string');\n}\nexports.validateModel = validateModel;\n/**\n * Validate an array of `IModel` objects.\n */\nfunction validateModels(models) {\n if (!Array.isArray(models)) {\n throw new Error('Invalid kernel list');\n }\n models.forEach(d => validateModel(d));\n}\nexports.validateModels = validateModels;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelSpecAPI = exports.KernelSpec = void 0;\nconst KernelSpec = __importStar(require(\"./kernelspec\"));\nexports.KernelSpec = KernelSpec;\nconst KernelSpecAPI = __importStar(require(\"./restapi\"));\nexports.KernelSpecAPI = KernelSpecAPI;\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=kernelspec.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelSpecManager = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst restapi = __importStar(require(\"./restapi\"));\nconst basemanager_1 = require(\"../basemanager\");\n/**\n * An implementation of a kernel spec manager.\n */\nclass KernelSpecManager extends basemanager_1.BaseManager {\n /**\n * Construct a new kernel spec manager.\n *\n * @param options - The default options for kernel.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n this._connectionFailure = new signaling_1.Signal(this);\n this._specs = null;\n this._specsChanged = new signaling_1.Signal(this);\n // Initialize internal data.\n this._ready = Promise.all([this.requestSpecs()])\n .then(_ => undefined)\n .catch(_ => undefined)\n .then(() => {\n if (this.isDisposed) {\n return;\n }\n this._isReady = true;\n });\n this._pollSpecs = new polling_1.Poll({\n auto: false,\n factory: () => this.requestSpecs(),\n frequency: {\n interval: 61 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:KernelSpecManager#specs`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n void this.ready.then(() => {\n void this._pollSpecs.start();\n });\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * Get the most recently fetched kernel specs.\n */\n get specs() {\n return this._specs;\n }\n /**\n * A signal emitted when the specs change.\n */\n get specsChanged() {\n return this._specsChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n this._pollSpecs.dispose();\n super.dispose();\n }\n /**\n * Force a refresh of the specs from the server.\n *\n * @returns A promise that resolves when the specs are fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshSpecs() {\n await this._pollSpecs.refresh();\n await this._pollSpecs.tick;\n }\n /**\n * Execute a request to the server to poll specs and update state.\n */\n async requestSpecs() {\n const specs = await restapi.getSpecs(this.serverSettings);\n if (this.isDisposed) {\n return;\n }\n if (!coreutils_1.JSONExt.deepEqual(specs, this._specs)) {\n this._specs = specs;\n this._specsChanged.emit(specs);\n }\n }\n}\nexports.KernelSpecManager = KernelSpecManager;\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSpecs = void 0;\nconst serverconnection_1 = require(\"../serverconnection\");\nconst validate_1 = require(\"./validate\");\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\n/**\n * The url for the kernelspec service.\n */\nconst KERNELSPEC_SERVICE_URL = 'api/kernelspecs';\n/**\n * Fetch all of the kernel specs.\n *\n * @param settings - The optional server settings.\n * @param useCache - Whether to use the cache. If false, always request.\n *\n * @returns A promise that resolves with the kernel specs.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernelspecs).\n */\nasync function getSpecs(settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, KERNELSPEC_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n return (0, validate_1.validateSpecModels)(data);\n}\nexports.getSpecs = getSpecs;\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateSpecModels = exports.validateSpecModel = void 0;\nconst validate_1 = require(\"../validate\");\n/**\n * Validate a server kernelspec model to a client side model.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction validateSpecModel(data) {\n const spec = data.spec;\n if (!spec) {\n throw new Error('Invalid kernel spec');\n }\n (0, validate_1.validateProperty)(data, 'name', 'string');\n (0, validate_1.validateProperty)(data, 'resources', 'object');\n (0, validate_1.validateProperty)(spec, 'language', 'string');\n (0, validate_1.validateProperty)(spec, 'display_name', 'string');\n (0, validate_1.validateProperty)(spec, 'argv', 'array');\n let metadata = null;\n if (spec.hasOwnProperty('metadata')) {\n (0, validate_1.validateProperty)(spec, 'metadata', 'object');\n metadata = spec.metadata;\n }\n let env = null;\n if (spec.hasOwnProperty('env')) {\n (0, validate_1.validateProperty)(spec, 'env', 'object');\n env = spec.env;\n }\n return {\n name: data.name,\n resources: data.resources,\n language: spec.language,\n display_name: spec.display_name,\n argv: spec.argv,\n metadata,\n env\n };\n}\nexports.validateSpecModel = validateSpecModel;\n/**\n * Validate a `Kernel.ISpecModels` object.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction validateSpecModels(data) {\n if (!data.hasOwnProperty('kernelspecs')) {\n throw new Error('No kernelspecs found');\n }\n let keys = Object.keys(data.kernelspecs);\n const kernelspecs = Object.create(null);\n let defaultSpec = data.default;\n for (let i = 0; i < keys.length; i++) {\n const ks = data.kernelspecs[keys[i]];\n try {\n kernelspecs[keys[i]] = validateSpecModel(ks);\n }\n catch (err) {\n // Remove the errant kernel spec.\n console.warn(`Removing errant kernel spec: ${keys[i]}`);\n }\n }\n keys = Object.keys(kernelspecs);\n if (!keys.length) {\n throw new Error('No valid kernelspecs found');\n }\n if (!defaultSpec ||\n typeof defaultSpec !== 'string' ||\n !(defaultSpec in kernelspecs)) {\n defaultSpec = keys[0];\n console.warn(`Default kernel not found, using '${keys[0]}'`);\n }\n return {\n default: defaultSpec,\n kernelspecs\n };\n}\nexports.validateSpecModels = validateSpecModels;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ServiceManager = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\nconst builder_1 = require(\"./builder\");\nconst contents_1 = require(\"./contents\");\nconst event_1 = require(\"./event\");\nconst kernel_1 = require(\"./kernel\");\nconst kernelspec_1 = require(\"./kernelspec\");\nconst nbconvert_1 = require(\"./nbconvert\");\nconst serverconnection_1 = require(\"./serverconnection\");\nconst session_1 = require(\"./session\");\nconst setting_1 = require(\"./setting\");\nconst terminal_1 = require(\"./terminal\");\nconst user_1 = require(\"./user\");\nconst workspace_1 = require(\"./workspace\");\n/**\n * A Jupyter services manager.\n */\nclass ServiceManager {\n /**\n * Construct a new services provider.\n */\n constructor(options = {}) {\n var _a, _b;\n this._isDisposed = false;\n this._connectionFailure = new signaling_1.Signal(this);\n this._isReady = false;\n const defaultDrive = options.defaultDrive;\n const serverSettings = (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n const standby = (_b = options.standby) !== null && _b !== void 0 ? _b : 'when-hidden';\n const normalized = { defaultDrive, serverSettings, standby };\n this.serverSettings = serverSettings;\n this.contents = options.contents || new contents_1.ContentsManager(normalized);\n this.events = options.events || new event_1.EventManager(normalized);\n this.kernels = options.kernels || new kernel_1.KernelManager(normalized);\n this.sessions =\n options.sessions ||\n new session_1.SessionManager({\n ...normalized,\n kernelManager: this.kernels\n });\n this.settings = options.settings || new setting_1.SettingManager(normalized);\n this.terminals = options.terminals || new terminal_1.TerminalManager(normalized);\n this.builder = options.builder || new builder_1.BuildManager(normalized);\n this.workspaces = options.workspaces || new workspace_1.WorkspaceManager(normalized);\n this.nbconvert = options.nbconvert || new nbconvert_1.NbConvertManager(normalized);\n this.kernelspecs = options.kernelspecs || new kernelspec_1.KernelSpecManager(normalized);\n this.user = options.user || new user_1.UserManager(normalized);\n // Proxy all connection failures from the individual service managers.\n this.kernelspecs.connectionFailure.connect(this._onConnectionFailure, this);\n this.sessions.connectionFailure.connect(this._onConnectionFailure, this);\n this.terminals.connectionFailure.connect(this._onConnectionFailure, this);\n // Define promises that need to be resolved before service manager is ready.\n const readyList = [this.sessions.ready, this.kernelspecs.ready];\n if (this.terminals.isAvailable()) {\n readyList.push(this.terminals.ready);\n }\n this._readyPromise = Promise.all(readyList).then(() => {\n this._isReady = true;\n });\n }\n /**\n * A signal emitted when there is a connection failure with the kernel.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Test whether the service manager is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n this.contents.dispose();\n this.events.dispose();\n this.sessions.dispose();\n this.terminals.dispose();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._readyPromise;\n }\n _onConnectionFailure(sender, err) {\n this._connectionFailure.emit(err);\n }\n}\nexports.ServiceManager = ServiceManager;\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NbConvertManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst serverconnection_1 = require(\"../serverconnection\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\n/**\n * The url for the lab nbconvert service.\n */\nconst NBCONVERT_SETTINGS_URL = 'api/nbconvert';\n/**\n * The nbconvert API service manager.\n */\nclass NbConvertManager {\n /**\n * Create a new nbconvert manager.\n */\n constructor(options = {}) {\n var _a;\n this._exportFormats = null;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * Fetch and cache the export formats from the expensive nbconvert handler.\n */\n async fetchExportFormats() {\n this._requestingFormats = new coreutils_2.PromiseDelegate();\n this._exportFormats = null;\n const base = this.serverSettings.baseUrl;\n const url = coreutils_1.URLExt.join(base, NBCONVERT_SETTINGS_URL);\n const { serverSettings } = this;\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n const exportList = {};\n const keys = Object.keys(data);\n keys.forEach(function (key) {\n const mimeType = data[key].output_mimetype;\n exportList[key] = { output_mimetype: mimeType };\n });\n this._exportFormats = exportList;\n this._requestingFormats.resolve(exportList);\n return exportList;\n }\n /**\n * Get the list of export formats, preferring pre-cached ones.\n */\n async getExportFormats(force = true) {\n if (this._requestingFormats) {\n return this._requestingFormats.promise;\n }\n if (force || !this._exportFormats) {\n return await this.fetchExportFormats();\n }\n return this._exportFormats;\n }\n}\nexports.NbConvertManager = NbConvertManager;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ServerConnection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nlet WEBSOCKET;\nif (typeof window === 'undefined') {\n // Mangle the require statements so it does not get picked up in the\n // browser assets.\n WEBSOCKET = require('ws');\n}\nelse {\n WEBSOCKET = WebSocket;\n}\n/**\n * The namespace for ServerConnection functions.\n *\n * #### Notes\n * This is only intended to manage communication with the Jupyter server.\n *\n * The default values can be used in a JupyterLab or Jupyter Notebook context.\n *\n * We use `token` authentication if available, falling back on an XSRF\n * cookie if one has been provided on the `document`.\n *\n * A content type of `'application/json'` is added when using authentication\n * and there is no body data to allow the server to prevent malicious forms.\n */\nvar ServerConnection;\n(function (ServerConnection) {\n /**\n * Create a settings object given a subset of options.\n *\n * @param options - An optional partial set of options.\n *\n * @returns The full settings object.\n */\n function makeSettings(options) {\n return Private.makeSettings(options);\n }\n ServerConnection.makeSettings = makeSettings;\n /**\n * Make an request to the notebook server.\n *\n * @param url - The url for the request.\n *\n * @param init - The initialization options for the request.\n *\n * @param settings - The server settings to apply to the request.\n *\n * @returns a Promise that resolves with the response.\n *\n * @throws If the url of the request is not a notebook server url.\n *\n * #### Notes\n * The `url` must start with `settings.baseUrl`. The `init` settings are\n * merged with `settings.init`, with `init` taking precedence.\n * The headers in the two objects are not merged.\n * If there is no body data, we set the content type to `application/json`\n * because it is required by the Notebook server.\n */\n function makeRequest(url, init, settings) {\n return Private.handleRequest(url, init, settings);\n }\n ServerConnection.makeRequest = makeRequest;\n /**\n * A wrapped error for a fetch response.\n */\n class ResponseError extends Error {\n /**\n * Create a ResponseError from a response, handling the traceback and message\n * as appropriate.\n *\n * @param response The response object.\n *\n * @returns A promise that resolves with a `ResponseError` object.\n */\n static async create(response) {\n try {\n const data = await response.json();\n const { message, traceback } = data;\n if (traceback) {\n console.error(traceback);\n }\n return new ResponseError(response, message !== null && message !== void 0 ? message : ResponseError._defaultMessage(response), traceback !== null && traceback !== void 0 ? traceback : '');\n }\n catch (e) {\n console.debug(e);\n return new ResponseError(response);\n }\n }\n /**\n * Create a new response error.\n */\n constructor(response, message = ResponseError._defaultMessage(response), traceback = '') {\n super(message);\n this.response = response;\n this.traceback = traceback;\n }\n static _defaultMessage(response) {\n return `Invalid response: ${response.status} ${response.statusText}`;\n }\n }\n ServerConnection.ResponseError = ResponseError;\n /**\n * A wrapped error for a network error.\n */\n class NetworkError extends TypeError {\n /**\n * Create a new network error.\n */\n constructor(original) {\n super(original.message);\n this.stack = original.stack;\n }\n }\n ServerConnection.NetworkError = NetworkError;\n})(ServerConnection = exports.ServerConnection || (exports.ServerConnection = {}));\n/**\n * The namespace for module private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Handle the server connection settings, returning a new value.\n */\n function makeSettings(options = {}) {\n var _a;\n const pageBaseUrl = coreutils_1.PageConfig.getBaseUrl();\n const pageWsUrl = coreutils_1.PageConfig.getWsUrl();\n const baseUrl = coreutils_1.URLExt.normalize(options.baseUrl) || pageBaseUrl;\n let wsUrl = options.wsUrl;\n // Prefer the default wsUrl if we are using the default baseUrl.\n if (!wsUrl && baseUrl === pageBaseUrl) {\n wsUrl = pageWsUrl;\n }\n // Otherwise convert the baseUrl to a wsUrl if possible.\n if (!wsUrl && baseUrl.indexOf('http') === 0) {\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n // Otherwise fall back on the default wsUrl.\n wsUrl = wsUrl !== null && wsUrl !== void 0 ? wsUrl : pageWsUrl;\n return {\n init: { cache: 'no-store', credentials: 'same-origin' },\n fetch,\n Headers,\n Request,\n WebSocket: WEBSOCKET,\n token: coreutils_1.PageConfig.getToken(),\n appUrl: coreutils_1.PageConfig.getOption('appUrl'),\n appendToken: typeof window === 'undefined' ||\n (typeof process !== 'undefined' &&\n ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.JEST_WORKER_ID) !== undefined) ||\n coreutils_1.URLExt.getHostName(pageBaseUrl) !== coreutils_1.URLExt.getHostName(wsUrl),\n ...options,\n baseUrl,\n wsUrl\n };\n }\n Private.makeSettings = makeSettings;\n /**\n * Handle a request.\n *\n * @param url - The url for the request.\n *\n * @param init - The overrides for the request init.\n *\n * @param settings - The settings object for the request.\n *\n * #### Notes\n * The `url` must start with `settings.baseUrl`. The `init` settings\n * take precedence over `settings.init`.\n */\n function handleRequest(url, init, settings) {\n var _a;\n // Handle notebook server requests.\n if (url.indexOf(settings.baseUrl) !== 0) {\n throw new Error('Can only be used for notebook server requests');\n }\n // Use explicit cache buster when `no-store` is set since\n // not all browsers use it properly.\n const cache = (_a = init.cache) !== null && _a !== void 0 ? _a : settings.init.cache;\n if (cache === 'no-store') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache\n url += (/\\?/.test(url) ? '&' : '?') + new Date().getTime();\n }\n const request = new settings.Request(url, { ...settings.init, ...init });\n // Handle authentication. Authentication can be overdetermined by\n // settings token and XSRF token.\n let authenticated = false;\n if (settings.token) {\n authenticated = true;\n request.headers.append('Authorization', `token ${settings.token}`);\n }\n if (typeof document !== 'undefined' && (document === null || document === void 0 ? void 0 : document.cookie)) {\n const xsrfToken = getCookie('_xsrf');\n if (xsrfToken !== undefined) {\n authenticated = true;\n request.headers.append('X-XSRFToken', xsrfToken);\n }\n }\n // Set the content type if there is no given data and we are\n // using an authenticated connection.\n if (!request.headers.has('Content-Type') && authenticated) {\n request.headers.set('Content-Type', 'application/json');\n }\n // Use `call` to avoid a `TypeError` in the browser.\n return settings.fetch.call(null, request).catch((e) => {\n // Convert the TypeError into a more specific error.\n throw new ServerConnection.NetworkError(e);\n });\n // TODO: *this* is probably where we need a system-wide connectionFailure\n // signal we can hook into.\n }\n Private.handleRequest = handleRequest;\n /**\n * Get a cookie from the document.\n */\n function getCookie(name) {\n // From http://www.tornadoweb.org/en/stable/guide/security.html\n const matches = document.cookie.match('\\\\b' + name + '=([^;]*)\\\\b');\n return matches === null || matches === void 0 ? void 0 : matches[1];\n }\n})(Private || (Private = {}));\n//# sourceMappingURL=serverconnection.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SessionConnection = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst restapi_1 = require(\"./restapi\");\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * Session object for accessing the session REST api. The session\n * should be used to start kernels and then shut them down -- for\n * all other kernel operations, the kernel object should be used.\n */\nclass SessionConnection {\n /**\n * Construct a new session.\n */\n constructor(options) {\n var _a, _b, _c, _d;\n this._id = '';\n this._path = '';\n this._name = '';\n this._type = '';\n this._kernel = null;\n this._isDisposed = false;\n this._disposed = new signaling_1.Signal(this);\n this._kernelChanged = new signaling_1.Signal(this);\n this._statusChanged = new signaling_1.Signal(this);\n this._connectionStatusChanged = new signaling_1.Signal(this);\n this._pendingInput = new signaling_1.Signal(this);\n this._iopubMessage = new signaling_1.Signal(this);\n this._unhandledMessage = new signaling_1.Signal(this);\n this._anyMessage = new signaling_1.Signal(this);\n this._propertyChanged = new signaling_1.Signal(this);\n this._id = options.model.id;\n this._name = options.model.name;\n this._path = options.model.path;\n this._type = options.model.type;\n this._username = (_a = options.username) !== null && _a !== void 0 ? _a : '';\n this._clientId = (_b = options.clientId) !== null && _b !== void 0 ? _b : coreutils_1.UUID.uuid4();\n this._connectToKernel = options.connectToKernel;\n this._kernelConnectionOptions = (_c = options.kernelConnectionOptions) !== null && _c !== void 0 ? _c : {};\n this.serverSettings =\n (_d = options.serverSettings) !== null && _d !== void 0 ? _d : __1.ServerConnection.makeSettings();\n this.setupKernel(options.model.kernel);\n }\n /**\n * A signal emitted when the session is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * A signal emitted when the kernel changes.\n */\n get kernelChanged() {\n return this._kernelChanged;\n }\n /**\n * A signal proxied from the connection about the kernel status.\n */\n get statusChanged() {\n return this._statusChanged;\n }\n /**\n * A signal proxied from the kernel about the connection status.\n */\n get connectionStatusChanged() {\n return this._connectionStatusChanged;\n }\n /**\n * A signal proxied from the kernel pending input.\n */\n get pendingInput() {\n return this._pendingInput;\n }\n /**\n * A signal proxied from the kernel about iopub kernel messages.\n */\n get iopubMessage() {\n return this._iopubMessage;\n }\n /**\n * A signal proxied from the kernel for an unhandled kernel message.\n */\n get unhandledMessage() {\n return this._unhandledMessage;\n }\n /**\n * A signal proxied from the kernel emitted for any kernel message.\n *\n * #### Notes\n * The behavior is undefined if the message is modified during message\n * handling. As such, it should be treated as read-only.\n */\n get anyMessage() {\n return this._anyMessage;\n }\n /**\n * A signal emitted when a session property changes.\n */\n get propertyChanged() {\n return this._propertyChanged;\n }\n /**\n * Get the session id.\n */\n get id() {\n return this._id;\n }\n /**\n * Get the session kernel connection object.\n *\n * #### Notes\n * This is a read-only property, and can be altered by [changeKernel].\n */\n get kernel() {\n return this._kernel;\n }\n /**\n * Get the session path.\n */\n get path() {\n return this._path;\n }\n /**\n * Get the session type.\n */\n get type() {\n return this._type;\n }\n /**\n * Get the session name.\n */\n get name() {\n return this._name;\n }\n /**\n * Get the model associated with the session.\n */\n get model() {\n return {\n id: this.id,\n kernel: this.kernel && { id: this.kernel.id, name: this.kernel.name },\n path: this._path,\n type: this._type,\n name: this._name\n };\n }\n /**\n * Test whether the session has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Update the session based on a session model from the server.\n *\n * #### Notes\n * This only updates this session connection instance. Use `setPath`,\n * `setName`, `setType`, and `changeKernel` to change the session values on\n * the server.\n */\n update(model) {\n const oldModel = this.model;\n this._path = model.path;\n this._name = model.name;\n this._type = model.type;\n if ((this._kernel === null && model.kernel !== null) ||\n (this._kernel !== null && model.kernel === null) ||\n (this._kernel !== null &&\n model.kernel !== null &&\n this._kernel.id !== model.kernel.id)) {\n if (this._kernel !== null) {\n this._kernel.dispose();\n }\n const oldValue = this._kernel || null;\n this.setupKernel(model.kernel);\n const newValue = this._kernel || null;\n this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });\n }\n this._handleModelChange(oldModel);\n }\n /**\n * Dispose of the resources held by the session.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n if (this._kernel) {\n this._kernel.dispose();\n const oldValue = this._kernel;\n this._kernel = null;\n const newValue = this._kernel;\n this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });\n }\n signaling_1.Signal.clearData(this);\n }\n /**\n * Change the session path.\n *\n * @param path - The new session path.\n *\n * @returns A promise that resolves when the session has renamed.\n *\n * #### Notes\n * This uses the Jupyter REST API, and the response is validated.\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async setPath(path) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ path });\n }\n /**\n * Change the session name.\n */\n async setName(name) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ name });\n }\n /**\n * Change the session type.\n */\n async setType(type) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ type });\n }\n /**\n * Change the kernel.\n *\n * @param options - The name or id of the new kernel.\n *\n * #### Notes\n * This shuts down the existing kernel and creates a new kernel,\n * keeping the existing session ID and session path.\n */\n async changeKernel(options) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ kernel: options });\n return this.kernel;\n }\n /**\n * Kill the kernel and shutdown the session.\n *\n * @returns - The promise fulfilled on a valid response from the server.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions), and validates the response.\n * Disposes of the session and emits a [sessionDied] signal on success.\n */\n async shutdown() {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await (0, restapi_1.shutdownSession)(this.id, this.serverSettings);\n this.dispose();\n }\n /**\n * Create a new kernel connection and connect to its signals.\n *\n * #### Notes\n * This method is not meant to be subclassed.\n */\n setupKernel(model) {\n if (model === null) {\n this._kernel = null;\n return;\n }\n const kc = this._connectToKernel({\n ...this._kernelConnectionOptions,\n model,\n username: this._username,\n clientId: this._clientId,\n serverSettings: this.serverSettings\n });\n this._kernel = kc;\n kc.statusChanged.connect(this.onKernelStatus, this);\n kc.connectionStatusChanged.connect(this.onKernelConnectionStatus, this);\n kc.pendingInput.connect(this.onPendingInput, this);\n kc.unhandledMessage.connect(this.onUnhandledMessage, this);\n kc.iopubMessage.connect(this.onIOPubMessage, this);\n kc.anyMessage.connect(this.onAnyMessage, this);\n }\n /**\n * Handle to changes in the Kernel status.\n */\n onKernelStatus(sender, state) {\n this._statusChanged.emit(state);\n }\n /**\n * Handle to changes in the Kernel status.\n */\n onKernelConnectionStatus(sender, state) {\n this._connectionStatusChanged.emit(state);\n }\n /**\n * Handle a change in the pendingInput.\n */\n onPendingInput(sender, state) {\n this._pendingInput.emit(state);\n }\n /**\n * Handle iopub kernel messages.\n */\n onIOPubMessage(sender, msg) {\n this._iopubMessage.emit(msg);\n }\n /**\n * Handle unhandled kernel messages.\n */\n onUnhandledMessage(sender, msg) {\n this._unhandledMessage.emit(msg);\n }\n /**\n * Handle any kernel messages.\n */\n onAnyMessage(sender, args) {\n this._anyMessage.emit(args);\n }\n /**\n * Send a PATCH to the server, updating the session path or the kernel.\n */\n async _patch(body) {\n const model = await (0, restapi_1.updateSession)({ ...body, id: this._id }, this.serverSettings);\n this.update(model);\n return model;\n }\n /**\n * Handle a change to the model.\n */\n _handleModelChange(oldModel) {\n if (oldModel.name !== this._name) {\n this._propertyChanged.emit('name');\n }\n if (oldModel.type !== this._type) {\n this._propertyChanged.emit('type');\n }\n if (oldModel.path !== this._path) {\n this._propertyChanged.emit('path');\n }\n }\n}\nexports.SessionConnection = SessionConnection;\n//# sourceMappingURL=default.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SessionAPI = exports.Session = void 0;\nconst Session = __importStar(require(\"./session\"));\nexports.Session = Session;\nconst SessionAPI = __importStar(require(\"./restapi\"));\nexports.SessionAPI = SessionAPI;\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SessionManager = void 0;\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"../serverconnection\");\nconst basemanager_1 = require(\"../basemanager\");\nconst default_1 = require(\"./default\");\nconst restapi_1 = require(\"./restapi\");\n/**\n * An implementation of a session manager.\n */\nclass SessionManager extends basemanager_1.BaseManager {\n /**\n * Construct a new session manager.\n *\n * @param options - The default options for each session.\n */\n constructor(options) {\n var _a;\n super(options);\n this._isReady = false;\n this._sessionConnections = new Set();\n this._models = new Map();\n this._runningChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // We define these here so they bind `this` correctly\n this._connectToKernel = (options) => {\n return this._kernelManager.connectTo(options);\n };\n this._kernelManager = options.kernelManager;\n // Start model polling with exponential backoff.\n this._pollModels = new polling_1.Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:SessionManager#models`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n if (this._kernelManager.isActive) {\n await this._kernelManager.ready;\n }\n this._isReady = true;\n })();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * A signal emitted when the running sessions change.\n */\n get runningChanged() {\n return this._runningChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._models.clear();\n this._sessionConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n /*\n * Connect to a running session. See also [[connectToSession]].\n */\n connectTo(options) {\n const sessionConnection = new default_1.SessionConnection({\n ...options,\n connectToKernel: this._connectToKernel,\n serverSettings: this.serverSettings\n });\n this._onStarted(sessionConnection);\n if (!this._models.has(options.model.id)) {\n // We trust the user to connect to an existing session, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return sessionConnection;\n }\n /**\n * Create an iterator over the most recent running sessions.\n *\n * @returns A new iterator over the running sessions.\n */\n running() {\n return this._models.values();\n }\n /**\n * Force a refresh of the running sessions.\n *\n * @returns A promise that with the list of running sessions.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n async refreshRunning() {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n /**\n * Start a new session. See also [[startNewSession]].\n *\n * @param createOptions - Options for creating the session\n *\n * @param connectOptions - Options for connecting to the session\n */\n async startNew(createOptions, connectOptions = {}) {\n const model = await (0, restapi_1.startSession)(createOptions, this.serverSettings);\n await this.refreshRunning();\n return this.connectTo({ ...connectOptions, model });\n }\n /**\n * Shut down a session by id.\n */\n async shutdown(id) {\n await (0, restapi_1.shutdownSession)(id, this.serverSettings);\n await this.refreshRunning();\n }\n /**\n * Shut down all sessions.\n *\n * @returns A promise that resolves when all of the kernels are shut down.\n */\n async shutdownAll() {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n // Shut down all models.\n await Promise.all([...this._models.keys()].map(id => (0, restapi_1.shutdownSession)(id, this.serverSettings)));\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n /**\n * Find a session associated with a path and stop it if it is the only session\n * using that kernel.\n *\n * @param path - The path in question.\n *\n * @returns A promise that resolves when the relevant sessions are stopped.\n */\n async stopIfNeeded(path) {\n try {\n const sessions = await (0, restapi_1.listRunning)(this.serverSettings);\n const matches = sessions.filter(value => value.path === path);\n if (matches.length === 1) {\n const id = matches[0].id;\n await this.shutdown(id);\n }\n }\n catch (error) {\n /* Always succeed. */\n }\n }\n /**\n * Find a session by id.\n */\n async findById(id) {\n if (this._models.has(id)) {\n return this._models.get(id);\n }\n await this.refreshRunning();\n return this._models.get(id);\n }\n /**\n * Find a session by path.\n */\n async findByPath(path) {\n for (const m of this._models.values()) {\n if (m.path === path) {\n return m;\n }\n }\n await this.refreshRunning();\n for (const m of this._models.values()) {\n if (m.path === path) {\n return m;\n }\n }\n return undefined;\n }\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n async requestRunning() {\n var _a, _b;\n let models;\n try {\n models = await (0, restapi_1.listRunning)(this.serverSettings);\n }\n catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof serverconnection_1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n if (this.isDisposed) {\n return;\n }\n if (this._models.size === models.length &&\n models.every(model => {\n var _a, _b, _c, _d;\n const existing = this._models.get(model.id);\n if (!existing) {\n return false;\n }\n return (((_a = existing.kernel) === null || _a === void 0 ? void 0 : _a.id) === ((_b = model.kernel) === null || _b === void 0 ? void 0 : _b.id) &&\n ((_c = existing.kernel) === null || _c === void 0 ? void 0 : _c.name) === ((_d = model.kernel) === null || _d === void 0 ? void 0 : _d.name) &&\n existing.name === model.name &&\n existing.path === model.path &&\n existing.type === model.type);\n })) {\n // Identical models list (presuming models does not contain duplicate\n // ids), so just return\n return;\n }\n this._models = new Map(models.map(x => [x.id, x]));\n this._sessionConnections.forEach(sc => {\n if (this._models.has(sc.id)) {\n sc.update(this._models.get(sc.id));\n }\n else {\n sc.dispose();\n }\n });\n this._runningChanged.emit(models);\n }\n /**\n * Handle a session starting.\n */\n _onStarted(sessionConnection) {\n this._sessionConnections.add(sessionConnection);\n sessionConnection.disposed.connect(this._onDisposed, this);\n sessionConnection.propertyChanged.connect(this._onChanged, this);\n sessionConnection.kernelChanged.connect(this._onChanged, this);\n }\n _onDisposed(sessionConnection) {\n this._sessionConnections.delete(sessionConnection);\n // A session termination emission could mean the server session is deleted,\n // or that the session JS object is disposed and the session still exists on\n // the server, so we refresh from the server to make sure we reflect the\n // server state.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n _onChanged() {\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n}\nexports.SessionManager = SessionManager;\n/**\n * The namespace for `SessionManager` class statics.\n */\n(function (SessionManager) {\n /**\n * A no-op session manager to be used when starting sessions is not supported.\n */\n class NoopManager extends SessionManager {\n constructor() {\n super(...arguments);\n this._readyPromise = new Promise(() => {\n /* no-op */\n });\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return false;\n }\n /**\n * Used for testing.\n */\n get parentReady() {\n return super.ready;\n }\n /**\n * Start a new session - throw an error since it is not supported.\n */\n async startNew(createOptions, connectOptions = {}) {\n return Promise.reject(new Error('Not implemented in no-op Session Manager'));\n }\n /*\n * Connect to a running session - throw an error since it is not supported.\n */\n connectTo(options) {\n throw Error('Not implemented in no-op Session Manager');\n }\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready() {\n return this.parentReady.then(() => this._readyPromise);\n }\n /**\n * Shut down a session by id - throw an error since it is not supported.\n */\n async shutdown(id) {\n return Promise.reject(new Error('Not implemented in no-op Session Manager'));\n }\n /**\n * Execute a request to the server to poll running sessions and update state.\n */\n async requestRunning() {\n return Promise.resolve();\n }\n }\n SessionManager.NoopManager = NoopManager;\n})(SessionManager = exports.SessionManager || (exports.SessionManager = {}));\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.updateSession = exports.startSession = exports.getSessionModel = exports.shutdownSession = exports.getSessionUrl = exports.listRunning = exports.SESSION_SERVICE_URL = void 0;\nconst serverconnection_1 = require(\"../serverconnection\");\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst validate_1 = require(\"./validate\");\n/**\n * The url for the session service.\n */\nexports.SESSION_SERVICE_URL = 'api/sessions';\n/**\n * List the running sessions.\n */\nasync function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.SESSION_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid Session list');\n }\n data.forEach(m => {\n (0, validate_1.updateLegacySessionModel)(m);\n (0, validate_1.validateModel)(m);\n });\n return data;\n}\nexports.listRunning = listRunning;\n/**\n * Get a session url.\n */\nfunction getSessionUrl(baseUrl, id) {\n return coreutils_1.URLExt.join(baseUrl, exports.SESSION_SERVICE_URL, id);\n}\nexports.getSessionUrl = getSessionUrl;\n/**\n * Shut down a session by id.\n */\nasync function shutdownSession(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n var _a;\n const url = getSessionUrl(settings.baseUrl, id);\n const init = { method: 'DELETE' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const data = await response.json();\n const msg = (_a = data.message) !== null && _a !== void 0 ? _a : `The session \"${id}\"\" does not exist on the server`;\n console.warn(msg);\n }\n else if (response.status === 410) {\n throw new serverconnection_1.ServerConnection.ResponseError(response, 'The kernel was deleted but the session was not');\n }\n else if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.shutdownSession = shutdownSession;\n/**\n * Get a full session model from the server by session id string.\n */\nasync function getSessionModel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = getSessionUrl(settings.baseUrl, id);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.updateLegacySessionModel)(data);\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.getSessionModel = getSessionModel;\n/**\n * Create a new session, or return an existing session if the session path\n * already exists.\n */\nasync function startSession(options, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.SESSION_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify(options)\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.updateLegacySessionModel)(data);\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.startSession = startSession;\n/**\n * Send a PATCH to the server, updating the session path or the kernel.\n */\nasync function updateSession(model, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = getSessionUrl(settings.baseUrl, model.id);\n const init = {\n method: 'PATCH',\n body: JSON.stringify(model)\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.updateLegacySessionModel)(data);\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.updateSession = updateSession;\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=session.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateModels = exports.updateLegacySessionModel = exports.validateModel = void 0;\nconst validate_1 = require(\"../kernel/validate\");\nconst validate_2 = require(\"../validate\");\n/**\n * Validate an `Session.IModel` object.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction validateModel(data) {\n (0, validate_2.validateProperty)(data, 'id', 'string');\n (0, validate_2.validateProperty)(data, 'type', 'string');\n (0, validate_2.validateProperty)(data, 'name', 'string');\n (0, validate_2.validateProperty)(data, 'path', 'string');\n (0, validate_2.validateProperty)(data, 'kernel', 'object');\n (0, validate_1.validateModel)(data.kernel);\n}\nexports.validateModel = validateModel;\n/**\n * Update model from legacy session data.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction updateLegacySessionModel(data) {\n if (data.path === undefined && data.notebook !== undefined) {\n data.path = data.notebook.path;\n data.type = 'notebook';\n data.name = '';\n }\n}\nexports.updateLegacySessionModel = updateLegacySessionModel;\n/**\n * Validate an array of `Session.IModel` objects.\n */\nfunction validateModels(models) {\n if (!Array.isArray(models)) {\n throw new Error('Invalid session list');\n }\n models.forEach(d => validateModel(d));\n}\nexports.validateModels = validateModels;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SettingManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst statedb_1 = require(\"@jupyterlab/statedb\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the lab settings service.\n */\nconst SERVICE_SETTINGS_URL = 'api/settings';\n/**\n * The settings API service manager.\n */\nclass SettingManager extends statedb_1.DataConnector {\n /**\n * Create a new setting manager.\n */\n constructor(options = {}) {\n var _a;\n super();\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * Fetch a plugin's settings.\n *\n * @param id - The plugin's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async fetch(id) {\n if (!id) {\n throw new Error('Plugin `id` parameter is required for settings fetch.');\n }\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n // Assert what type the server response is returning.\n return response.json();\n }\n /**\n * Fetch the list of all plugin setting bundles.\n *\n * @returns A promise that resolves if successful.\n */\n async list(query) {\n var _a, _b, _c, _d;\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, '', query === 'ids');\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n throw new ResponseError(response);\n }\n const json = await response.json();\n const ids = (_b = (_a = json === null || json === void 0 ? void 0 : json['settings']) === null || _a === void 0 ? void 0 : _a.map((plugin) => plugin.id)) !== null && _b !== void 0 ? _b : [];\n let values = [];\n if (!query) {\n values =\n (_d = (_c = json === null || json === void 0 ? void 0 : json['settings']) === null || _c === void 0 ? void 0 : _c.map((plugin) => {\n plugin.data = { composite: {}, user: {} };\n return plugin;\n })) !== null && _d !== void 0 ? _d : [];\n }\n return { ids, values };\n }\n /**\n * Save a plugin's settings.\n *\n * @param id - The plugin's ID.\n *\n * @param raw - The user setting values as a raw string of JSON with comments.\n *\n * @returns A promise that resolves if successful.\n */\n async save(id, raw) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n // NOTE: 'raw' is JSON5 (not valid JSON), so we encode it as a string in a valid JSON body\n const init = { body: JSON.stringify({ raw }), method: 'PUT' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n throw new ResponseError(response);\n }\n }\n}\nexports.SettingManager = SettingManager;\n/**\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Get the url for a plugin's settings.\n */\n function url(base, id, idsOnly) {\n const idsOnlyParam = idsOnly\n ? coreutils_1.URLExt.objectToQueryString({ ids_only: true })\n : '';\n return `${coreutils_1.URLExt.join(base, SERVICE_SETTINGS_URL, id)}${idsOnlyParam}`;\n }\n Private.url = url;\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = WebSocket;\n//# sourceMappingURL=ws.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TerminalConnection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst restapi_1 = require(\"./restapi\");\n/**\n * An implementation of a terminal interface.\n */\nclass TerminalConnection {\n /**\n * Construct a new terminal session.\n */\n constructor(options) {\n var _a;\n /**\n * Create the terminal websocket connection and add socket status handlers.\n *\n * #### Notes\n * You are responsible for updating the connection status as appropriate.\n */\n this._createSocket = () => {\n this._errorIfDisposed();\n // Make sure the socket is clear\n this._clearSocket();\n // Update the connection status to reflect opening a new connection.\n this._updateConnectionStatus('connecting');\n const name = this._name;\n const settings = this.serverSettings;\n let url = coreutils_1.URLExt.join(settings.wsUrl, 'terminals', 'websocket', encodeURIComponent(name));\n // If token authentication is in use.\n const token = settings.token;\n if (settings.appendToken && token !== '') {\n url = url + `?token=${encodeURIComponent(token)}`;\n }\n this._ws = new settings.WebSocket(url);\n this._ws.onmessage = this._onWSMessage;\n this._ws.onclose = this._onWSClose;\n this._ws.onerror = this._onWSClose;\n };\n // Websocket messages events are defined as variables to bind `this`\n this._onWSMessage = (event) => {\n if (this._isDisposed) {\n return;\n }\n const data = JSON.parse(event.data);\n // Handle a disconnect message.\n if (data[0] === 'disconnect') {\n this.dispose();\n }\n if (this._connectionStatus === 'connecting') {\n // After reconnection, ignore all messages until a 'setup' message\n // before we are truly connected. Setting the connection status to\n // connected only then means that if we do not get a setup message\n // before our retry timeout, we will delete the websocket and try again.\n if (data[0] === 'setup') {\n this._updateConnectionStatus('connected');\n }\n return;\n }\n this._messageReceived.emit({\n type: data[0],\n content: data.slice(1)\n });\n };\n this._onWSClose = (event) => {\n console.warn(`Terminal websocket closed: ${event.code}`);\n if (!this.isDisposed) {\n this._reconnect();\n }\n };\n this._connectionStatus = 'connecting';\n this._connectionStatusChanged = new signaling_1.Signal(this);\n this._isDisposed = false;\n this._disposed = new signaling_1.Signal(this);\n this._messageReceived = new signaling_1.Signal(this);\n this._reconnectTimeout = null;\n this._ws = null;\n this._noOp = () => {\n /* no-op */\n };\n this._reconnectLimit = 7;\n this._reconnectAttempt = 0;\n this._pendingMessages = [];\n this._name = options.model.name;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings();\n this._createSocket();\n }\n /**\n * A signal emitted when the session is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * A signal emitted when a message is received from the server.\n */\n get messageReceived() {\n return this._messageReceived;\n }\n /**\n * Get the name of the terminal session.\n */\n get name() {\n return this._name;\n }\n /**\n * Get the model for the terminal session.\n */\n get model() {\n return { name: this._name };\n }\n /**\n * Test whether the session is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the session.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n this._updateConnectionStatus('disconnected');\n this._clearSocket();\n signaling_1.Signal.clearData(this);\n }\n /**\n * Send a message to the terminal session.\n *\n * #### Notes\n * If the connection is down, the message will be queued for sending when\n * the connection comes back up.\n */\n send(message) {\n this._sendMessage(message);\n }\n /**\n * Send a message on the websocket, or possibly queue for later sending.\n *\n * @param queue - whether to queue the message if it cannot be sent\n */\n _sendMessage(message, queue = true) {\n if (this._isDisposed || !message.content) {\n return;\n }\n if (this.connectionStatus === 'connected' && this._ws) {\n const msg = [message.type, ...message.content];\n this._ws.send(JSON.stringify(msg));\n }\n else if (queue) {\n this._pendingMessages.push(message);\n }\n else {\n throw new Error(`Could not send message: ${JSON.stringify(message)}`);\n }\n }\n /**\n * Send pending messages to the kernel.\n */\n _sendPending() {\n // We check to make sure we are still connected each time. For\n // example, if a websocket buffer overflows, it may close, so we should\n // stop sending messages.\n while (this.connectionStatus === 'connected' &&\n this._pendingMessages.length > 0) {\n this._sendMessage(this._pendingMessages[0], false);\n // We shift the message off the queue after the message is sent so that\n // if there is an exception, the message is still pending.\n this._pendingMessages.shift();\n }\n }\n /**\n * Reconnect to a terminal.\n *\n * #### Notes\n * This may try multiple times to reconnect to a terminal, and will sever\n * any existing connection.\n */\n reconnect() {\n this._errorIfDisposed();\n const result = new coreutils_2.PromiseDelegate();\n // Set up a listener for the connection status changing, which accepts or\n // rejects after the retries are done.\n const fulfill = (sender, status) => {\n if (status === 'connected') {\n result.resolve();\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n else if (status === 'disconnected') {\n result.reject(new Error('Terminal connection disconnected'));\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n };\n this.connectionStatusChanged.connect(fulfill, this);\n // Reset the reconnect limit so we start the connection attempts fresh\n this._reconnectAttempt = 0;\n // Start the reconnection process, which will also clear any existing\n // connection.\n this._reconnect();\n // Return the promise that should resolve on connection or reject if the\n // retries don't work.\n return result.promise;\n }\n /**\n * Attempt a connection if we have not exhausted connection attempts.\n */\n _reconnect() {\n this._errorIfDisposed();\n // Clear any existing reconnection attempt\n clearTimeout(this._reconnectTimeout);\n // Update the connection status and schedule a possible reconnection.\n if (this._reconnectAttempt < this._reconnectLimit) {\n this._updateConnectionStatus('connecting');\n // The first reconnect attempt should happen immediately, and subsequent\n // attempts should pick a random number in a growing range so that we\n // don't overload the server with synchronized reconnection attempts\n // across multiple kernels.\n const timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));\n console.error(`Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`);\n this._reconnectTimeout = setTimeout(this._createSocket, timeout);\n this._reconnectAttempt += 1;\n }\n else {\n this._updateConnectionStatus('disconnected');\n }\n // Clear the websocket event handlers and the socket itself.\n this._clearSocket();\n }\n /**\n * Forcefully clear the socket state.\n *\n * #### Notes\n * This will clear all socket state without calling any handlers and will\n * not update the connection status. If you call this method, you are\n * responsible for updating the connection status as needed and recreating\n * the socket if you plan to reconnect.\n */\n _clearSocket() {\n if (this._ws !== null) {\n // Clear the websocket event handlers and the socket itself.\n this._ws.onopen = this._noOp;\n this._ws.onclose = this._noOp;\n this._ws.onerror = this._noOp;\n this._ws.onmessage = this._noOp;\n this._ws.close();\n this._ws = null;\n }\n }\n /**\n * Shut down the terminal session.\n */\n async shutdown() {\n await (0, restapi_1.shutdownTerminal)(this.name, this.serverSettings);\n this.dispose();\n }\n /**\n * Clone the current terminal connection.\n */\n clone() {\n return new TerminalConnection(this);\n }\n /**\n * Handle connection status changes.\n */\n _updateConnectionStatus(connectionStatus) {\n if (this._connectionStatus === connectionStatus) {\n return;\n }\n this._connectionStatus = connectionStatus;\n // If we are not 'connecting', stop any reconnection attempts.\n if (connectionStatus !== 'connecting') {\n this._reconnectAttempt = 0;\n clearTimeout(this._reconnectTimeout);\n }\n // Send the pending messages if we just connected.\n if (connectionStatus === 'connected') {\n this._sendPending();\n }\n // Notify others that the connection status changed.\n this._connectionStatusChanged.emit(connectionStatus);\n }\n /**\n * Utility function to throw an error if this instance is disposed.\n */\n _errorIfDisposed() {\n if (this.isDisposed) {\n throw new Error('Terminal connection is disposed');\n }\n }\n /**\n * A signal emitted when the terminal connection status changes.\n */\n get connectionStatusChanged() {\n return this._connectionStatusChanged;\n }\n /**\n * The current connection status of the terminal connection.\n */\n get connectionStatus() {\n return this._connectionStatus;\n }\n}\nexports.TerminalConnection = TerminalConnection;\nvar Private;\n(function (Private) {\n /**\n * Get the url for a terminal.\n */\n function getTermUrl(baseUrl, name) {\n return coreutils_1.URLExt.join(baseUrl, restapi_1.TERMINAL_SERVICE_URL, encodeURIComponent(name));\n }\n Private.getTermUrl = getTermUrl;\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n Private.getRandomIntInclusive = getRandomIntInclusive;\n})(Private || (Private = {}));\n//# sourceMappingURL=default.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TerminalAPI = exports.Terminal = void 0;\nconst Terminal = __importStar(require(\"./terminal\"));\nexports.Terminal = Terminal;\nconst TerminalAPI = __importStar(require(\"./restapi\"));\nexports.TerminalAPI = TerminalAPI;\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TerminalManager = void 0;\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst basemanager_1 = require(\"../basemanager\");\nconst restapi_1 = require(\"./restapi\");\nconst default_1 = require(\"./default\");\n/**\n * A terminal session manager.\n */\nclass TerminalManager extends basemanager_1.BaseManager {\n /**\n * Construct a new terminal manager.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n // As an optimization, we unwrap the models to just store the names.\n this._names = [];\n this._terminalConnections = new Set();\n this._runningChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // Check if terminals are available\n if (!this.isAvailable()) {\n this._ready = Promise.reject('Terminals unavailable');\n this._ready.catch(_ => undefined);\n return;\n }\n // Start polling with exponential backoff.\n this._pollModels = new polling_1.Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:TerminalManager#models`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n this._isReady = true;\n })();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * A signal emitted when the running terminals change.\n */\n get runningChanged() {\n return this._runningChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._names.length = 0;\n this._terminalConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n /**\n * Whether the terminal service is available.\n */\n isAvailable() {\n return (0, restapi_1.isAvailable)();\n }\n /*\n * Connect to a running terminal.\n *\n * @param options - The options used to connect to the terminal.\n *\n * @returns The new terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be used.\n */\n connectTo(options) {\n const terminalConnection = new default_1.TerminalConnection({\n ...options,\n serverSettings: this.serverSettings\n });\n this._onStarted(terminalConnection);\n if (!this._names.includes(options.model.name)) {\n // We trust the user to connect to an existing session, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return terminalConnection;\n }\n /**\n * Create an iterator over the most recent running terminals.\n *\n * @returns A new iterator over the running terminals.\n */\n running() {\n return this._models[Symbol.iterator]();\n }\n /**\n * Force a refresh of the running terminals.\n *\n * @returns A promise that with the list of running terminals.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshRunning() {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n /**\n * Create a new terminal session.\n *\n * @param options - The options used to create the terminal.\n *\n * @returns A promise that resolves with the terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be used unless overridden in the\n * options.\n */\n async startNew(options) {\n const model = await (0, restapi_1.startNew)(this.serverSettings, options === null || options === void 0 ? void 0 : options.name, options === null || options === void 0 ? void 0 : options.cwd);\n await this.refreshRunning();\n return this.connectTo({ model });\n }\n /**\n * Shut down a terminal session by name.\n */\n async shutdown(name) {\n await (0, restapi_1.shutdownTerminal)(name, this.serverSettings);\n await this.refreshRunning();\n }\n /**\n * Shut down all terminal sessions.\n *\n * @returns A promise that resolves when all of the sessions are shut down.\n */\n async shutdownAll() {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n // Shut down all models.\n await Promise.all(this._names.map(name => (0, restapi_1.shutdownTerminal)(name, this.serverSettings)));\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n /**\n * Execute a request to the server to poll running terminals and update state.\n */\n async requestRunning() {\n var _a, _b;\n let models;\n try {\n models = await (0, restapi_1.listRunning)(this.serverSettings);\n }\n catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof __1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n if (this.isDisposed) {\n return;\n }\n const names = models.map(({ name }) => name).sort();\n if (names === this._names) {\n // Identical models list, so just return\n return;\n }\n this._names = names;\n this._terminalConnections.forEach(tc => {\n if (!names.includes(tc.name)) {\n tc.dispose();\n }\n });\n this._runningChanged.emit(this._models);\n }\n /**\n * Handle a session starting.\n */\n _onStarted(terminalConnection) {\n this._terminalConnections.add(terminalConnection);\n terminalConnection.disposed.connect(this._onDisposed, this);\n }\n /**\n * Handle a session terminating.\n */\n _onDisposed(terminalConnection) {\n this._terminalConnections.delete(terminalConnection);\n // Update the running models to make sure we reflect the server state\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n get _models() {\n return this._names.map(name => {\n return { name };\n });\n }\n}\nexports.TerminalManager = TerminalManager;\n/**\n * The namespace for TerminalManager statics.\n */\n(function (TerminalManager) {\n /**\n * A no-op terminal manager to be used when starting terminals is not supported.\n */\n class NoopManager extends TerminalManager {\n constructor() {\n super(...arguments);\n this._readyPromise = new Promise(() => {\n /* no-op */\n });\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return false;\n }\n /**\n * Used for testing.\n */\n get parentReady() {\n return super.ready;\n }\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready() {\n return this.parentReady.then(() => this._readyPromise);\n }\n /**\n * Create a new terminal session - throw an error since it is not supported.\n *\n */\n async startNew(options) {\n return Promise.reject(new Error('Not implemented in no-op Terminal Manager'));\n }\n /*\n * Connect to a running terminal - throw an error since it is not supported.\n */\n connectTo(options) {\n throw Error('Not implemented in no-op Terminal Manager');\n }\n /**\n * Shut down a session by id - throw an error since it is not supported.\n */\n async shutdown(id) {\n return Promise.reject(new Error('Not implemented in no-op Terminal Manager'));\n }\n /**\n * Execute a request to the server to poll running sessions and update state.\n */\n async requestRunning() {\n return Promise.resolve();\n }\n }\n TerminalManager.NoopManager = NoopManager;\n})(TerminalManager = exports.TerminalManager || (exports.TerminalManager = {}));\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shutdownTerminal = exports.listRunning = exports.startNew = exports.isAvailable = exports.TERMINAL_SERVICE_URL = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the terminal service.\n */\nexports.TERMINAL_SERVICE_URL = 'api/terminals';\n/**\n * Whether the terminal service is available.\n */\nfunction isAvailable() {\n const available = String(coreutils_1.PageConfig.getOption('terminalsAvailable'));\n return available.toLowerCase() === 'true';\n}\nexports.isAvailable = isAvailable;\n/**\n * Start a new terminal session.\n *\n * @param settings - The server settings to use.\n *\n * @param name - The name of the target terminal.\n *\n * @param cwd - The path in which the terminal will start.\n *\n * @returns A promise that resolves with the session model.\n */\nasync function startNew(settings = serverconnection_1.ServerConnection.makeSettings(), name, cwd) {\n Private.errorIfNotAvailable();\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify({ name, cwd })\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n // TODO: Validate model\n return data;\n}\nexports.startNew = startNew;\n/**\n * List the running terminal sessions.\n *\n * @param settings - The server settings to use.\n *\n * @returns A promise that resolves with the list of running session models.\n */\nasync function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {\n Private.errorIfNotAvailable();\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid terminal list');\n }\n // TODO: validate each model\n return data;\n}\nexports.listRunning = listRunning;\n/**\n * Shut down a terminal session by name.\n *\n * @param name - The name of the target session.\n *\n * @param settings - The server settings to use.\n *\n * @returns A promise that resolves when the session is shut down.\n */\nasync function shutdownTerminal(name, settings = serverconnection_1.ServerConnection.makeSettings()) {\n var _a;\n Private.errorIfNotAvailable();\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL, name);\n const init = { method: 'DELETE' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const data = await response.json();\n const msg = (_a = data.message) !== null && _a !== void 0 ? _a : `The terminal session \"${name}\"\" does not exist on the server`;\n console.warn(msg);\n }\n else if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.shutdownTerminal = shutdownTerminal;\nvar Private;\n(function (Private) {\n /**\n * Throw an error if terminals are not available.\n */\n function errorIfNotAvailable() {\n if (!isAvailable()) {\n throw new Error('Terminals Unavailable');\n }\n }\n Private.errorIfNotAvailable = errorIfNotAvailable;\n})(Private || (Private = {}));\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAvailable = void 0;\nconst restapi_1 = require(\"./restapi\");\nObject.defineProperty(exports, \"isAvailable\", { enumerable: true, get: function () { return restapi_1.isAvailable; } });\n//# sourceMappingURL=terminal.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UserManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"../serverconnection\");\nconst basemanager_1 = require(\"../basemanager\");\n/**\n * The url for the lab workspaces service.\n */\nconst SERVICE_USER_URL = 'api/me';\n/**\n * The service's ID.\n * Used to uniquely identify the poll, and\n * the item in local storage.\n */\nconst SERVICE_ID = '@jupyterlab/services:UserManager#user';\n/**\n * The user API service manager.\n */\nclass UserManager extends basemanager_1.BaseManager {\n /**\n * Create a new user manager.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n this._userChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // Initialize internal data.\n this._ready = this.requestUser()\n .then(() => {\n if (this.isDisposed) {\n return;\n }\n this._isReady = true;\n })\n .catch(_ => \n // Return a promise that will never resolve, so user service is never ready\n // This typically occurs when the backend has no user service\n new Promise(() => {\n // no-op\n }));\n this._pollSpecs = new polling_1.Poll({\n auto: false,\n factory: () => this.requestUser(),\n frequency: {\n interval: 61 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: SERVICE_ID,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n void this.ready.then(() => {\n void this._pollSpecs.start();\n });\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * Get the most recently fetched identity.\n */\n get identity() {\n return this._identity;\n }\n /**\n * Get the most recently fetched permissions.\n */\n get permissions() {\n return this._permissions;\n }\n /**\n * A signal emitted when the user changes.\n */\n get userChanged() {\n return this._userChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n this._pollSpecs.dispose();\n super.dispose();\n }\n /**\n * Force a refresh of the specs from the server.\n *\n * @returns A promise that resolves when the specs are fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshUser() {\n await this._pollSpecs.refresh();\n await this._pollSpecs.tick;\n }\n /**\n * Execute a request to the server to poll the user and update state.\n */\n async requestUser() {\n if (this.isDisposed) {\n return;\n }\n const { baseUrl } = this.serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const url = coreutils_1.URLExt.join(baseUrl, SERVICE_USER_URL);\n const response = await makeRequest(url, {}, this.serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n const oldUser = {\n identity: this._identity,\n permissions: this._permissions\n };\n const newUser = await response.json();\n const identity = newUser.identity;\n // store the color and initials for the user\n // this info is not provided by the server\n const { localStorage } = window;\n const data = localStorage.getItem(SERVICE_ID);\n if (data && (!identity.initials || !identity.color)) {\n const localUser = JSON.parse(data);\n identity.initials =\n identity.initials ||\n localUser.initials ||\n identity.name.substring(0, 1);\n identity.color =\n identity.color || localUser.color || Private.getRandomColor();\n }\n if (!coreutils_2.JSONExt.deepEqual(newUser, oldUser)) {\n this._identity = identity;\n this._permissions = newUser.permissions;\n localStorage.setItem(SERVICE_ID, JSON.stringify(identity));\n this._userChanged.emit(newUser);\n }\n }\n}\nexports.UserManager = UserManager;\n/**\n * A namespace for module-private functionality.\n *\n * Note: We do not want to export this function\n * to move it to css variables in the Theme.\n */\nvar Private;\n(function (Private) {\n /**\n * Predefined colors for users\n */\n const userColors = [\n 'var(--jp-collaborator-color1)',\n 'var(--jp-collaborator-color2)',\n 'var(--jp-collaborator-color3)',\n 'var(--jp-collaborator-color4)',\n 'var(--jp-collaborator-color5)',\n 'var(--jp-collaborator-color6)',\n 'var(--jp-collaborator-color7)'\n ];\n /**\n * Get a random color from the list of colors.\n */\n Private.getRandomColor = () => userColors[Math.floor(Math.random() * userColors.length)];\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateProperty = void 0;\n/**\n * Validate a property as being on an object, and optionally\n * of a given type and among a given set of values.\n */\nfunction validateProperty(\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nobject, name, typeName, values = []) {\n if (!object.hasOwnProperty(name)) {\n throw Error(`Missing property '${name}'`);\n }\n const value = object[name];\n if (typeName !== void 0) {\n let valid = true;\n switch (typeName) {\n case 'array':\n valid = Array.isArray(value);\n break;\n case 'object':\n valid = typeof value !== 'undefined';\n break;\n default:\n valid = typeof value === typeName;\n }\n if (!valid) {\n throw new Error(`Property '${name}' is not of type '${typeName}'`);\n }\n if (values.length > 0) {\n let valid = true;\n switch (typeName) {\n case 'string':\n case 'number':\n case 'boolean':\n valid = values.includes(value);\n break;\n default:\n valid = values.findIndex(v => v === value) >= 0;\n break;\n }\n if (!valid) {\n throw new Error(`Property '${name}' is not one of the valid values ${JSON.stringify(values)}`);\n }\n }\n }\n}\nexports.validateProperty = validateProperty;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkspaceManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst statedb_1 = require(\"@jupyterlab/statedb\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the lab workspaces service.\n */\nconst SERVICE_WORKSPACES_URL = 'api/workspaces';\n/**\n * The workspaces API service manager.\n */\nclass WorkspaceManager extends statedb_1.DataConnector {\n /**\n * Create a new workspace manager.\n */\n constructor(options = {}) {\n var _a;\n super();\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * Fetch a workspace.\n *\n * @param id - The workspace's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async fetch(id) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n return response.json();\n }\n /**\n * Fetch the list of workspace IDs that exist on the server.\n *\n * @returns A promise that resolves if successful.\n */\n async list() {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, '');\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n const result = await response.json();\n return result.workspaces;\n }\n /**\n * Remove a workspace from the server.\n *\n * @param id - The workspaces's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async remove(id) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const init = { method: 'DELETE' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n const err = await ResponseError.create(response);\n throw err;\n }\n }\n /**\n * Save a workspace.\n *\n * @param id - The workspace's ID.\n *\n * @param workspace - The workspace being saved.\n *\n * @returns A promise that resolves if successful.\n */\n async save(id, workspace) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const init = { body: JSON.stringify(workspace), method: 'PUT' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n const err = await ResponseError.create(response);\n throw err;\n }\n }\n}\nexports.WorkspaceManager = WorkspaceManager;\n/**\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Get the url for a workspace.\n */\n function url(base, id) {\n return coreutils_1.URLExt.join(base, SERVICE_WORKSPACES_URL, id);\n }\n Private.url = url;\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ActivityMonitor = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * A class that monitors activity on a signal.\n */\nclass ActivityMonitor {\n /**\n * Construct a new activity monitor.\n */\n constructor(options) {\n this._timer = -1;\n this._timeout = -1;\n this._isDisposed = false;\n this._activityStopped = new signaling_1.Signal(this);\n options.signal.connect(this._onSignalFired, this);\n this._timeout = options.timeout || 1000;\n }\n /**\n * A signal emitted when activity has ceased.\n */\n get activityStopped() {\n return this._activityStopped;\n }\n /**\n * The timeout associated with the monitor, in milliseconds.\n */\n get timeout() {\n return this._timeout;\n }\n set timeout(value) {\n this._timeout = value;\n }\n /**\n * Test whether the monitor has been disposed.\n *\n * #### Notes\n * This is a read-only property.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources used by the activity monitor.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * A signal handler for the monitored signal.\n */\n _onSignalFired(sender, args) {\n clearTimeout(this._timer);\n this._sender = sender;\n this._args = args;\n this._timer = setTimeout(() => {\n this._activityStopped.emit({\n sender: this._sender,\n args: this._args\n });\n }, this._timeout);\n }\n}\nexports.ActivityMonitor = ActivityMonitor;\n//# sourceMappingURL=activitymonitor.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module coreutils\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./activitymonitor\"), exports);\n__exportStar(require(\"./interfaces\"), exports);\n__exportStar(require(\"./markdowncodeblocks\"), exports);\n__exportStar(require(\"./pageconfig\"), exports);\n__exportStar(require(\"./path\"), exports);\n__exportStar(require(\"./signal\"), exports);\n__exportStar(require(\"./text\"), exports);\n__exportStar(require(\"./time\"), exports);\n__exportStar(require(\"./url\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=interfaces.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MarkdownCodeBlocks = void 0;\n/**\n * The namespace for code block functions which help\n * in extract code from markdown text\n */\nvar MarkdownCodeBlocks;\n(function (MarkdownCodeBlocks) {\n MarkdownCodeBlocks.CODE_BLOCK_MARKER = '```';\n const markdownExtensions = [\n '.markdown',\n '.mdown',\n '.mkdn',\n '.md',\n '.mkd',\n '.mdwn',\n '.mdtxt',\n '.mdtext',\n '.text',\n '.txt',\n '.Rmd'\n ];\n class MarkdownCodeBlock {\n constructor(startLine) {\n this.startLine = startLine;\n this.code = '';\n this.endLine = -1;\n }\n }\n MarkdownCodeBlocks.MarkdownCodeBlock = MarkdownCodeBlock;\n /**\n * Check whether the given file extension is a markdown extension\n * @param extension - A file extension\n *\n * @returns true/false depending on whether this is a supported markdown extension\n */\n function isMarkdown(extension) {\n return markdownExtensions.indexOf(extension) > -1;\n }\n MarkdownCodeBlocks.isMarkdown = isMarkdown;\n /**\n * Construct all code snippets from current text\n * (this could be potentially optimized if we can cache and detect differences)\n * @param text - A string to parse codeblocks from\n *\n * @returns An array of MarkdownCodeBlocks.\n */\n function findMarkdownCodeBlocks(text) {\n if (!text || text === '') {\n return [];\n }\n const lines = text.split('\\n');\n const codeBlocks = [];\n let currentBlock = null;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n const lineContainsMarker = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER) === 0;\n const constructingBlock = currentBlock != null;\n // Skip this line if it is not part of any code block and doesn't contain a marker.\n if (!lineContainsMarker && !constructingBlock) {\n continue;\n }\n // Check if we are already constructing a code block.\n if (!constructingBlock) {\n // Start constructing a new code block.\n currentBlock = new MarkdownCodeBlock(lineIndex);\n // Check whether this is a single line code block of the form ```a = 10```.\n const firstIndex = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const lastIndex = line.lastIndexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const isSingleLine = firstIndex !== lastIndex;\n if (isSingleLine) {\n currentBlock.code = line.substring(firstIndex + MarkdownCodeBlocks.CODE_BLOCK_MARKER.length, lastIndex);\n currentBlock.endLine = lineIndex;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n }\n else if (currentBlock) {\n if (lineContainsMarker) {\n // End of block, finish it up.\n currentBlock.endLine = lineIndex - 1;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n else {\n // Append the current line.\n currentBlock.code += line + '\\n';\n }\n }\n }\n return codeBlocks;\n }\n MarkdownCodeBlocks.findMarkdownCodeBlocks = findMarkdownCodeBlocks;\n})(MarkdownCodeBlocks = exports.MarkdownCodeBlocks || (exports.MarkdownCodeBlocks = {}));\n//# sourceMappingURL=markdowncodeblocks.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PageConfig = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst minimist_1 = __importDefault(require(\"minimist\"));\nconst url_1 = require(\"./url\");\n/**\n * The namespace for `PageConfig` functions.\n */\nvar PageConfig;\n(function (PageConfig) {\n /**\n * Get global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n *\n * @returns The config value or an empty string if not found.\n *\n * #### Notes\n * All values are treated as strings.\n * For browser based applications, it is assumed that the page HTML\n * includes a script tag with the id `jupyter-config-data` containing the\n * configuration as valid JSON. In order to support the classic Notebook,\n * we fall back on checking for `body` data of the given `name`.\n *\n * For node applications, it is assumed that the process was launched\n * with a `--jupyter-config-data` option pointing to a JSON settings\n * file.\n */\n function getOption(name) {\n if (configData) {\n return configData[name] || getBodyData(name);\n }\n configData = Object.create(null);\n let found = false;\n // Use script tag if available.\n if (typeof document !== 'undefined' && document) {\n const el = document.getElementById('jupyter-config-data');\n if (el) {\n configData = JSON.parse(el.textContent || '');\n found = true;\n }\n }\n // Otherwise use CLI if given.\n if (!found && typeof process !== 'undefined' && process.argv) {\n try {\n const cli = (0, minimist_1.default)(process.argv.slice(2));\n const path = require('path');\n let fullPath = '';\n if ('jupyter-config-data' in cli) {\n fullPath = path.resolve(cli['jupyter-config-data']);\n }\n else if ('JUPYTER_CONFIG_DATA' in process.env) {\n fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);\n }\n if (fullPath) {\n // Force Webpack to ignore this require.\n // eslint-disable-next-line\n configData = eval('require')(fullPath);\n }\n }\n catch (e) {\n console.error(e);\n }\n }\n if (!coreutils_1.JSONExt.isObject(configData)) {\n configData = Object.create(null);\n }\n else {\n for (const key in configData) {\n // PageConfig expects strings\n if (typeof configData[key] !== 'string') {\n configData[key] = JSON.stringify(configData[key]);\n }\n }\n }\n return configData[name] || getBodyData(name);\n }\n PageConfig.getOption = getOption;\n /**\n * Set global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n * @param value - The value to set the option to.\n *\n * @returns The last config value or an empty string if it doesn't exist.\n */\n function setOption(name, value) {\n const last = getOption(name);\n configData[name] = value;\n return last;\n }\n PageConfig.setOption = setOption;\n /**\n * Get the base url for a Jupyter application, or the base url of the page.\n */\n function getBaseUrl() {\n return url_1.URLExt.normalize(getOption('baseUrl') || '/');\n }\n PageConfig.getBaseUrl = getBaseUrl;\n /**\n * Get the tree url for a JupyterLab application.\n */\n function getTreeUrl() {\n return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }\n PageConfig.getTreeUrl = getTreeUrl;\n /**\n * Get the base url for sharing links (usually baseUrl)\n */\n function getShareUrl() {\n return url_1.URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }\n PageConfig.getShareUrl = getShareUrl;\n /**\n * Get the tree url for shareable links.\n * Usually the same as treeUrl,\n * but overrideable e.g. when sharing with JupyterHub.\n */\n function getTreeShareUrl() {\n return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(), getOption('treeUrl')));\n }\n PageConfig.getTreeShareUrl = getTreeShareUrl;\n /**\n * Create a new URL given an optional mode and tree path.\n *\n * This is used to create URLS when the mode or tree path change as the user\n * changes mode or the current document in the main area. If fields in\n * options are omitted, the value in PageConfig will be used.\n *\n * @param options - IGetUrlOptions for the new path.\n */\n function getUrl(options) {\n var _a, _b, _c, _d;\n let path = options.toShare ? getShareUrl() : getBaseUrl();\n const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : getOption('mode');\n const workspace = (_b = options.workspace) !== null && _b !== void 0 ? _b : getOption('workspace');\n const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';\n path = url_1.URLExt.join(path, labOrDoc);\n if (workspace !== PageConfig.defaultWorkspace) {\n path = url_1.URLExt.join(path, 'workspaces', encodeURIComponent((_c = getOption('workspace')) !== null && _c !== void 0 ? _c : PageConfig.defaultWorkspace));\n }\n const treePath = (_d = options.treePath) !== null && _d !== void 0 ? _d : getOption('treePath');\n if (treePath) {\n path = url_1.URLExt.join(path, 'tree', url_1.URLExt.encodeParts(treePath));\n }\n return path;\n }\n PageConfig.getUrl = getUrl;\n PageConfig.defaultWorkspace = 'default';\n /**\n * Get the base websocket url for a Jupyter application, or an empty string.\n */\n function getWsUrl(baseUrl) {\n let wsUrl = getOption('wsUrl');\n if (!wsUrl) {\n baseUrl = baseUrl ? url_1.URLExt.normalize(baseUrl) : getBaseUrl();\n if (baseUrl.indexOf('http') !== 0) {\n return '';\n }\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n return url_1.URLExt.normalize(wsUrl);\n }\n PageConfig.getWsUrl = getWsUrl;\n /**\n * Returns the URL converting this notebook to a certain\n * format with nbconvert.\n */\n function getNBConvertURL({ path, format, download }) {\n const notebookPath = url_1.URLExt.encodeParts(path);\n const url = url_1.URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);\n if (download) {\n return url + '?download=true';\n }\n return url;\n }\n PageConfig.getNBConvertURL = getNBConvertURL;\n /**\n * Get the authorization token for a Jupyter application.\n */\n function getToken() {\n return getOption('token') || getBodyData('jupyterApiToken');\n }\n PageConfig.getToken = getToken;\n /**\n * Get the Notebook version info [major, minor, patch].\n */\n function getNotebookVersion() {\n const notebookVersion = getOption('notebookVersion');\n if (notebookVersion === '') {\n return [0, 0, 0];\n }\n return JSON.parse(notebookVersion);\n }\n PageConfig.getNotebookVersion = getNotebookVersion;\n /**\n * Private page config data for the Jupyter application.\n */\n let configData = null;\n /**\n * Get a url-encoded item from `body.data` and decode it\n * We should never have any encoded URLs anywhere else in code\n * until we are building an actual request.\n */\n function getBodyData(key) {\n if (typeof document === 'undefined' || !document.body) {\n return '';\n }\n const val = document.body.dataset[key];\n if (typeof val === 'undefined') {\n return '';\n }\n return decodeURIComponent(val);\n }\n /**\n * The namespace for page config `Extension` functions.\n */\n let Extension;\n (function (Extension) {\n /**\n * Populate an array from page config.\n *\n * @param key - The page config key (e.g., `deferredExtensions`).\n *\n * #### Notes\n * This is intended for `deferredExtensions` and `disabledExtensions`.\n */\n function populate(key) {\n try {\n const raw = getOption(key);\n if (raw) {\n return JSON.parse(raw);\n }\n }\n catch (error) {\n console.warn(`Unable to parse ${key}.`, error);\n }\n return [];\n }\n /**\n * The collection of deferred extensions in page config.\n */\n Extension.deferred = populate('deferredExtensions');\n /**\n * The collection of disabled extensions in page config.\n */\n Extension.disabled = populate('disabledExtensions');\n /**\n * Returns whether a plugin is deferred.\n *\n * @param id - The plugin ID.\n */\n function isDeferred(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.deferred.some(val => val === id || (extName && val === extName));\n }\n Extension.isDeferred = isDeferred;\n /**\n * Returns whether a plugin is disabled.\n *\n * @param id - The plugin ID.\n */\n function isDisabled(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.disabled.some(val => val === id || (extName && val === extName));\n }\n Extension.isDisabled = isDisabled;\n })(Extension = PageConfig.Extension || (PageConfig.Extension = {}));\n})(PageConfig = exports.PageConfig || (exports.PageConfig = {}));\n//# sourceMappingURL=pageconfig.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PathExt = void 0;\nconst path_1 = require(\"path\");\n/**\n * The namespace for path-related functions.\n *\n * Note that Jupyter server paths do not start with a leading slash.\n */\nvar PathExt;\n(function (PathExt) {\n /**\n * Join all arguments together and normalize the resulting path.\n * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n *\n * @param paths - The string paths to join.\n */\n function join(...paths) {\n const path = path_1.posix.join(...paths);\n return path === '.' ? '' : removeSlash(path);\n }\n PathExt.join = join;\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * Often used to extract the file name from a fully qualified path.\n *\n * @param path - The path to evaluate.\n *\n * @param ext - An extension to remove from the result.\n */\n function basename(path, ext) {\n return path_1.posix.basename(path, ext);\n }\n PathExt.basename = basename;\n /**\n * Get the directory name of a path, similar to the Unix dirname command.\n * When an empty path is given, returns the root path.\n *\n * @param path - The file path.\n */\n function dirname(path) {\n const dir = removeSlash(path_1.posix.dirname(path));\n return dir === '.' ? '' : dir;\n }\n PathExt.dirname = dirname;\n /**\n * Get the extension of the path.\n *\n * @param path - The file path.\n *\n * @returns the extension of the file.\n *\n * #### Notes\n * The extension is the string from the last occurrence of the `.`\n * character to end of string in the last portion of the path, inclusive.\n * If there is no `.` in the last portion of the path, or if the first\n * character of the basename of path [[basename]] is `.`, then an\n * empty string is returned.\n */\n function extname(path) {\n return path_1.posix.extname(path);\n }\n PathExt.extname = extname;\n /**\n * Normalize a string path, reducing '..' and '.' parts.\n * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n * When an empty path is given, returns the root path.\n *\n * @param path - The string path to normalize.\n */\n function normalize(path) {\n if (path === '') {\n return '';\n }\n return removeSlash(path_1.posix.normalize(path));\n }\n PathExt.normalize = normalize;\n /**\n * Resolve a sequence of paths or path segments into an absolute path.\n * The root path in the application has no leading slash, so it is removed.\n *\n * @param parts - The paths to join.\n *\n * #### Notes\n * The right-most parameter is considered \\{to\\}. Other parameters are considered an array of \\{from\\}.\n *\n * Starting from leftmost \\{from\\} parameter, resolves \\{to\\} to an absolute path.\n *\n * If \\{to\\} isn't already absolute, \\{from\\} arguments are prepended in right to left order, until an absolute path is found. If after using all \\{from\\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n */\n function resolve(...parts) {\n return removeSlash(path_1.posix.resolve(...parts));\n }\n PathExt.resolve = resolve;\n /**\n * Solve the relative path from \\{from\\} to \\{to\\}.\n *\n * @param from - The source path.\n *\n * @param to - The target path.\n *\n * #### Notes\n * If from and to each resolve to the same path (after calling\n * path.resolve() on each), a zero-length string is returned.\n * If a zero-length string is passed as from or to, `/`\n * will be used instead of the zero-length strings.\n */\n function relative(from, to) {\n return removeSlash(path_1.posix.relative(from, to));\n }\n PathExt.relative = relative;\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * @param extension - the file extension.\n *\n * #### Notes\n * Adds a leading dot if not present and converts to lower case.\n */\n function normalizeExtension(extension) {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n PathExt.normalizeExtension = normalizeExtension;\n /**\n * Remove the leading slash from a path.\n *\n * @param path: the path from which to remove a leading slash.\n */\n function removeSlash(path) {\n if (path.indexOf('/') === 0) {\n path = path.slice(1);\n }\n return path;\n }\n PathExt.removeSlash = removeSlash;\n})(PathExt = exports.PathExt || (exports.PathExt = {}));\n//# sourceMappingURL=path.js.map","\"use strict\";\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.signalToPromise = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * Convert a signal into a promise for the first emitted value.\n *\n * @param signal - The signal we are listening to.\n * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)\n *\n * @returns a Promise that resolves with a `(sender, args)` pair.\n */\nfunction signalToPromise(signal, timeout) {\n const waitForSignal = new coreutils_1.PromiseDelegate();\n function cleanup() {\n signal.disconnect(slot);\n }\n function slot(sender, args) {\n cleanup();\n waitForSignal.resolve([sender, args]);\n }\n signal.connect(slot);\n if ((timeout !== null && timeout !== void 0 ? timeout : 0) > 0) {\n setTimeout(() => {\n cleanup();\n waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);\n }, timeout);\n }\n return waitForSignal.promise;\n}\nexports.signalToPromise = signalToPromise;\n//# sourceMappingURL=signal.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Text = void 0;\n/**\n * The namespace for text-related functions.\n */\nvar Text;\n(function (Text) {\n // javascript stores text as utf16 and string indices use \"code units\",\n // which stores high-codepoint characters as \"surrogate pairs\",\n // which occupy two indices in the javascript string.\n // We need to translate cursor_pos in the Jupyter protocol (in characters)\n // to js offset (with surrogate pairs taking two spots).\n const HAS_SURROGATES = '𝐚'.length > 1;\n /**\n * Convert a javascript string index into a unicode character offset\n *\n * @param jsIdx - The javascript string index (counting surrogate pairs)\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The unicode character offset\n */\n function jsIndexToCharIndex(jsIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return jsIdx;\n }\n let charIdx = jsIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n charIdx--;\n i++;\n }\n }\n }\n return charIdx;\n }\n Text.jsIndexToCharIndex = jsIndexToCharIndex;\n /**\n * Convert a unicode character offset to a javascript string index.\n *\n * @param charIdx - The index in unicode characters\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The js-native index\n */\n function charIndexToJsIndex(charIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return charIdx;\n }\n let jsIdx = charIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n jsIdx++;\n i++;\n }\n }\n }\n return jsIdx;\n }\n Text.charIndexToJsIndex = charIndexToJsIndex;\n /**\n * Given a 'snake-case', 'snake_case', 'snake:case', or\n * 'snake case' string, will return the camel case version: 'snakeCase'.\n *\n * @param str: the snake-case input string.\n *\n * @param upper: default = false. If true, the first letter of the\n * returned string will be capitalized.\n *\n * @returns the camel case version of the input string.\n */\n function camelCase(str, upper = false) {\n return str.replace(/^(\\w)|[\\s-_:]+(\\w)/g, function (match, p1, p2) {\n if (p2) {\n return p2.toUpperCase();\n }\n else {\n return upper ? p1.toUpperCase() : p1.toLowerCase();\n }\n });\n }\n Text.camelCase = camelCase;\n /**\n * Given a string, title case the words in the string.\n *\n * @param str: the string to title case.\n *\n * @returns the same string, but with each word capitalized.\n */\n function titleCase(str) {\n return (str || '')\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n Text.titleCase = titleCase;\n})(Text = exports.Text || (exports.Text = {}));\n//# sourceMappingURL=text.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Time = void 0;\n/**\n * A list of time units with their associated value in milliseconds.\n */\nconst UNITS = [\n { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },\n { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },\n { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },\n { name: 'hours', milliseconds: 60 * 60 * 1000 },\n { name: 'minutes', milliseconds: 60 * 1000 },\n { name: 'seconds', milliseconds: 1000 }\n];\n/**\n * The namespace for date functions.\n */\nvar Time;\n(function (Time) {\n /**\n * Convert a timestring to a human readable string (e.g. 'two minutes ago').\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function formatHuman(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' });\n const delta = new Date(value).getTime() - Date.now();\n for (let unit of UNITS) {\n const amount = Math.ceil(delta / unit.milliseconds);\n if (amount === 0) {\n continue;\n }\n return formatter.format(amount, unit.name);\n }\n return formatter.format(0, 'seconds');\n }\n Time.formatHuman = formatHuman;\n /**\n * Convenient helper to convert a timestring to a date format.\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function format(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.DateTimeFormat(lang, {\n dateStyle: 'short',\n timeStyle: 'short'\n });\n return formatter.format(new Date(value));\n }\n Time.format = format;\n})(Time = exports.Time || (exports.Time = {}));\n//# sourceMappingURL=time.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URLExt = void 0;\nconst path_1 = require(\"path\");\nconst url_parse_1 = __importDefault(require(\"url-parse\"));\n/**\n * The namespace for URL-related functions.\n */\nvar URLExt;\n(function (URLExt) {\n /**\n * Parse a url into a URL object.\n *\n * @param urlString - The URL string to parse.\n *\n * @returns A URL object.\n */\n function parse(url) {\n if (typeof document !== 'undefined' && document) {\n const a = document.createElement('a');\n a.href = url;\n return a;\n }\n return (0, url_parse_1.default)(url);\n }\n URLExt.parse = parse;\n /**\n * Parse URL and retrieve hostname\n *\n * @param url - The URL string to parse\n *\n * @returns a hostname string value\n */\n function getHostName(url) {\n return (0, url_parse_1.default)(url).hostname;\n }\n URLExt.getHostName = getHostName;\n function normalize(url) {\n return url && parse(url).toString();\n }\n URLExt.normalize = normalize;\n /**\n * Join a sequence of url components and normalizes as in node `path.join`.\n *\n * @param parts - The url components.\n *\n * @returns the joined url.\n */\n function join(...parts) {\n let u = (0, url_parse_1.default)(parts[0], {});\n // Schema-less URL can be only parsed as relative to a base URL\n // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326\n const isSchemaLess = u.protocol === '' && u.slashes;\n if (isSchemaLess) {\n u = (0, url_parse_1.default)(parts[0], 'https:' + parts[0]);\n }\n const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${u.auth}${u.auth ? '@' : ''}${u.host}`;\n // If there was a prefix, then the first path must start at the root.\n const path = path_1.posix.join(`${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`, ...parts.slice(1));\n return `${prefix}${path === '.' ? '' : path}`;\n }\n URLExt.join = join;\n /**\n * Encode the components of a multi-segment url.\n *\n * @param url - The url to encode.\n *\n * @returns the encoded url.\n *\n * #### Notes\n * Preserves the `'/'` separators.\n * Should not include the base url, since all parts are escaped.\n */\n function encodeParts(url) {\n return join(...url.split('/').map(encodeURIComponent));\n }\n URLExt.encodeParts = encodeParts;\n /**\n * Return a serialized object string suitable for a query.\n *\n * @param object - The source object.\n *\n * @returns an encoded url query.\n *\n * #### Notes\n * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).\n */\n function objectToQueryString(value) {\n const keys = Object.keys(value).filter(key => key.length > 0);\n if (!keys.length) {\n return '';\n }\n return ('?' +\n keys\n .map(key => {\n const content = encodeURIComponent(String(value[key]));\n return key + (content ? '=' + content : '');\n })\n .join('&'));\n }\n URLExt.objectToQueryString = objectToQueryString;\n /**\n * Return a parsed object that represents the values in a query string.\n */\n function queryStringToObject(value) {\n return value\n .replace(/^\\?/, '')\n .split('&')\n .reduce((acc, val) => {\n const [key, value] = val.split('=');\n if (key.length > 0) {\n acc[key] = decodeURIComponent(value || '');\n }\n return acc;\n }, {});\n }\n URLExt.queryStringToObject = queryStringToObject;\n /**\n * Test whether the url is a local url.\n *\n * #### Notes\n * This function returns `false` for any fully qualified url, including\n * `data:`, `file:`, and `//` protocol URLs.\n */\n function isLocal(url) {\n const { protocol } = parse(url);\n return ((!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&\n url.indexOf('/') !== 0);\n }\n URLExt.isLocal = isLocal;\n})(URLExt = exports.URLExt || (exports.URLExt = {}));\n//# sourceMappingURL=url.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DataConnector = void 0;\n/**\n * An abstract class that adheres to the data connector interface.\n *\n * @typeparam T - The basic entity response type a service's connector.\n *\n * @typeparam U - The basic entity request type, which is conventionally the\n * same as the response type but may be different if a service's implementation\n * requires input data to be different from output responses. Defaults to `T`.\n *\n * @typeparam V - The basic token applied to a request, conventionally a string\n * ID or filter, but may be set to a different type when an implementation\n * requires it. Defaults to `string`.\n *\n * @typeparam W - The type of the optional `query` parameter of the `list`\n * method. Defaults to `string`.\n *\n * #### Notes\n * The only abstract method in this class is the `fetch` method, which must be\n * reimplemented by all subclasses. The `remove` and `save` methods have a\n * default implementation that returns a promise that will always reject. This\n * class is a convenience superclass for connectors that only need to `fetch`.\n */\nclass DataConnector {\n /**\n * Retrieve the list of items available from the data connector.\n *\n * @param query - The optional query filter to apply to the connector request.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can list.\n */\n async list(query) {\n throw new Error('DataConnector#list method has not been implemented.');\n }\n /**\n * Remove a value using the data connector.\n *\n * @param id - The identifier for the data being removed.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can remove.\n */\n async remove(id) {\n throw new Error('DataConnector#remove method has not been implemented.');\n }\n /**\n * Save a value using the data connector.\n *\n * @param id - The identifier for the data being saved.\n *\n * @param value - The data being saved.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can save.\n */\n async save(id, value) {\n throw new Error('DataConnector#save method has not been implemented.');\n }\n}\nexports.DataConnector = DataConnector;\n//# sourceMappingURL=dataconnector.js.map","\"use strict\";\n/* -----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module statedb\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./dataconnector\"), exports);\n__exportStar(require(\"./interfaces\"), exports);\n__exportStar(require(\"./restorablepool\"), exports);\n__exportStar(require(\"./statedb\"), exports);\n__exportStar(require(\"./tokens\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=interfaces.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RestorablePool = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst properties_1 = require(\"@lumino/properties\");\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * An object pool that supports restoration.\n *\n * @typeparam T - The type of object being tracked.\n */\nclass RestorablePool {\n /**\n * Create a new restorable pool.\n *\n * @param options - The instantiation options for a restorable pool.\n */\n constructor(options) {\n this._added = new signaling_1.Signal(this);\n this._current = null;\n this._currentChanged = new signaling_1.Signal(this);\n this._hasRestored = false;\n this._isDisposed = false;\n this._objects = new Set();\n this._restore = null;\n this._restored = new coreutils_1.PromiseDelegate();\n this._updated = new signaling_1.Signal(this);\n this.namespace = options.namespace;\n }\n /**\n * A signal emitted when an object object is added.\n *\n * #### Notes\n * This signal will only fire when an object is added to the pool.\n * It will not fire if an object injected into the pool.\n */\n get added() {\n return this._added;\n }\n /**\n * The current object.\n *\n * #### Notes\n * The restorable pool does not set `current`. It is intended for client use.\n *\n * If `current` is set to an object that does not exist in the pool, it is a\n * no-op.\n */\n get current() {\n return this._current;\n }\n set current(obj) {\n if (this._current === obj) {\n return;\n }\n if (obj !== null && this._objects.has(obj)) {\n this._current = obj;\n this._currentChanged.emit(this._current);\n }\n }\n /**\n * A signal emitted when the current widget changes.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * Test whether the pool is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * A promise resolved when the restorable pool has been restored.\n */\n get restored() {\n return this._restored.promise;\n }\n /**\n * The number of objects held by the pool.\n */\n get size() {\n return this._objects.size;\n }\n /**\n * A signal emitted when an object is updated.\n */\n get updated() {\n return this._updated;\n }\n /**\n * Add a new object to the pool.\n *\n * @param obj - The object object being added.\n *\n * #### Notes\n * The object passed into the pool is added synchronously; its existence in\n * the pool can be checked with the `has()` method. The promise this method\n * returns resolves after the object has been added and saved to an underlying\n * restoration connector, if one is available.\n */\n async add(obj) {\n var _a, _b;\n if (obj.isDisposed) {\n const warning = 'A disposed object cannot be added.';\n console.warn(warning, obj);\n throw new Error(warning);\n }\n if (this._objects.has(obj)) {\n const warning = 'This object already exists in the pool.';\n console.warn(warning, obj);\n throw new Error(warning);\n }\n this._objects.add(obj);\n obj.disposed.connect(this._onInstanceDisposed, this);\n if (Private.injectedProperty.get(obj)) {\n return;\n }\n if (this._restore) {\n const { connector } = this._restore;\n const objName = this._restore.name(obj);\n if (objName) {\n const name = `${this.namespace}:${objName}`;\n const data = (_b = (_a = this._restore).args) === null || _b === void 0 ? void 0 : _b.call(_a, obj);\n Private.nameProperty.set(obj, name);\n await connector.save(name, { data });\n }\n }\n // Emit the added signal.\n this._added.emit(obj);\n }\n /**\n * Dispose of the resources held by the pool.\n *\n * #### Notes\n * Disposing a pool does not affect the underlying data in the data connector,\n * it simply disposes the client-side pool without making any connector calls.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._current = null;\n this._isDisposed = true;\n this._objects.clear();\n signaling_1.Signal.clearData(this);\n }\n /**\n * Find the first object in the pool that satisfies a filter function.\n *\n * @param - fn The filter function to call on each object.\n */\n find(fn) {\n const values = this._objects.values();\n for (const value of values) {\n if (fn(value)) {\n return value;\n }\n }\n return undefined;\n }\n /**\n * Iterate through each object in the pool.\n *\n * @param fn - The function to call on each object.\n */\n forEach(fn) {\n this._objects.forEach(fn);\n }\n /**\n * Filter the objects in the pool based on a predicate.\n *\n * @param fn - The function by which to filter.\n */\n filter(fn) {\n const filtered = [];\n this.forEach(obj => {\n if (fn(obj)) {\n filtered.push(obj);\n }\n });\n return filtered;\n }\n /**\n * Inject an object into the restorable pool without the pool handling its\n * restoration lifecycle.\n *\n * @param obj - The object to inject into the pool.\n */\n inject(obj) {\n Private.injectedProperty.set(obj, true);\n return this.add(obj);\n }\n /**\n * Check if this pool has the specified object.\n *\n * @param obj - The object whose existence is being checked.\n */\n has(obj) {\n return this._objects.has(obj);\n }\n /**\n * Restore the objects in this pool's namespace.\n *\n * @param options - The configuration options that describe restoration.\n *\n * @returns A promise that resolves when restoration has completed.\n *\n * #### Notes\n * This function should almost never be invoked by client code. Its primary\n * use case is to be invoked by a layout restorer plugin that handles\n * multiple restorable pools and, when ready, asks them each to restore their\n * respective objects.\n */\n async restore(options) {\n if (this._hasRestored) {\n throw new Error('This pool has already been restored.');\n }\n this._hasRestored = true;\n const { command, connector, registry, when } = options;\n const namespace = this.namespace;\n const promises = when\n ? [connector.list(namespace)].concat(when)\n : [connector.list(namespace)];\n this._restore = options;\n const [saved] = await Promise.all(promises);\n const values = await Promise.all(saved.ids.map(async (id, index) => {\n const value = saved.values[index];\n const args = value && value.data;\n if (args === undefined) {\n return connector.remove(id);\n }\n // Execute the command and if it fails, delete the state restore data.\n return registry\n .execute(command, args)\n .catch(() => connector.remove(id));\n }));\n this._restored.resolve();\n return values;\n }\n /**\n * Save the restore data for a given object.\n *\n * @param obj - The object being saved.\n */\n async save(obj) {\n var _a, _b;\n const injected = Private.injectedProperty.get(obj);\n if (!this._restore || !this.has(obj) || injected) {\n return;\n }\n const { connector } = this._restore;\n const objName = this._restore.name(obj);\n const oldName = Private.nameProperty.get(obj);\n const newName = objName ? `${this.namespace}:${objName}` : '';\n if (oldName && oldName !== newName) {\n await connector.remove(oldName);\n }\n // Set the name property irrespective of whether the new name is null.\n Private.nameProperty.set(obj, newName);\n if (newName) {\n const data = (_b = (_a = this._restore).args) === null || _b === void 0 ? void 0 : _b.call(_a, obj);\n await connector.save(newName, { data });\n }\n if (oldName !== newName) {\n this._updated.emit(obj);\n }\n }\n /**\n * Clean up after disposed objects.\n */\n _onInstanceDisposed(obj) {\n this._objects.delete(obj);\n if (obj === this._current) {\n this._current = null;\n this._currentChanged.emit(this._current);\n }\n if (Private.injectedProperty.get(obj)) {\n return;\n }\n if (!this._restore) {\n return;\n }\n const { connector } = this._restore;\n const name = Private.nameProperty.get(obj);\n if (name) {\n void connector.remove(name);\n }\n }\n}\nexports.RestorablePool = RestorablePool;\n/*\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * An attached property to indicate whether an object has been injected.\n */\n Private.injectedProperty = new properties_1.AttachedProperty({\n name: 'injected',\n create: () => false\n });\n /**\n * An attached property for an object's ID.\n */\n Private.nameProperty = new properties_1.AttachedProperty({\n name: 'name',\n create: () => ''\n });\n})(Private || (Private = {}));\n//# sourceMappingURL=restorablepool.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StateDB = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * The default concrete implementation of a state database.\n */\nclass StateDB {\n /**\n * Create a new state database.\n *\n * @param options - The instantiation options for a state database.\n */\n constructor(options = {}) {\n this._changed = new signaling_1.Signal(this);\n const { connector, transform } = options;\n this._connector = connector || new StateDB.Connector();\n if (!transform) {\n this._ready = Promise.resolve(undefined);\n }\n else {\n this._ready = transform.then(transformation => {\n const { contents, type } = transformation;\n switch (type) {\n case 'cancel':\n return;\n case 'clear':\n return this._clear();\n case 'merge':\n return this._merge(contents || {});\n case 'overwrite':\n return this._overwrite(contents || {});\n default:\n return;\n }\n });\n }\n }\n /**\n * A signal that emits the change type any time a value changes.\n */\n get changed() {\n return this._changed;\n }\n /**\n * Clear the entire database.\n */\n async clear() {\n await this._ready;\n await this._clear();\n }\n /**\n * Retrieve a saved bundle from the database.\n *\n * @param id - The identifier used to retrieve a data bundle.\n *\n * @returns A promise that bears a data payload if available.\n *\n * #### Notes\n * The `id` values of stored items in the state database are formatted:\n * `'namespace:identifier'`, which is the same convention that command\n * identifiers in JupyterLab use as well. While this is not a technical\n * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for\n * using the `list(namespace: string)` method.\n *\n * The promise returned by this method may be rejected if an error occurs in\n * retrieving the data. Non-existence of an `id` will succeed with the `value`\n * `undefined`.\n */\n async fetch(id) {\n await this._ready;\n return this._fetch(id);\n }\n /**\n * Retrieve all the saved bundles for a namespace.\n *\n * @param filter - The namespace prefix to retrieve.\n *\n * @returns A promise that bears a collection of payloads for a namespace.\n *\n * #### Notes\n * Namespaces are entirely conventional entities. The `id` values of stored\n * items in the state database are formatted: `'namespace:identifier'`, which\n * is the same convention that command identifiers in JupyterLab use as well.\n *\n * If there are any errors in retrieving the data, they will be logged to the\n * console in order to optimistically return any extant data without failing.\n * This promise will always succeed.\n */\n async list(namespace) {\n await this._ready;\n return this._list(namespace);\n }\n /**\n * Remove a value from the database.\n *\n * @param id - The identifier for the data being removed.\n *\n * @returns A promise that is rejected if remove fails and succeeds otherwise.\n */\n async remove(id) {\n await this._ready;\n await this._remove(id);\n this._changed.emit({ id, type: 'remove' });\n }\n /**\n * Save a value in the database.\n *\n * @param id - The identifier for the data being saved.\n *\n * @param value - The data being saved.\n *\n * @returns A promise that is rejected if saving fails and succeeds otherwise.\n *\n * #### Notes\n * The `id` values of stored items in the state database are formatted:\n * `'namespace:identifier'`, which is the same convention that command\n * identifiers in JupyterLab use as well. While this is not a technical\n * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for\n * using the `list(namespace: string)` method.\n */\n async save(id, value) {\n await this._ready;\n await this._save(id, value);\n this._changed.emit({ id, type: 'save' });\n }\n /**\n * Return a serialized copy of the state database's entire contents.\n *\n * @returns A promise that resolves with the database contents as JSON.\n */\n async toJSON() {\n await this._ready;\n const { ids, values } = await this._list();\n return values.reduce((acc, val, idx) => {\n acc[ids[idx]] = val;\n return acc;\n }, {});\n }\n /**\n * Clear the entire database.\n */\n async _clear() {\n await Promise.all((await this._list()).ids.map(id => this._remove(id)));\n }\n /**\n * Fetch a value from the database.\n */\n async _fetch(id) {\n const value = await this._connector.fetch(id);\n if (value) {\n return JSON.parse(value).v;\n }\n }\n /**\n * Fetch a list from the database.\n */\n async _list(namespace = '') {\n const { ids, values } = await this._connector.list(namespace);\n return {\n ids,\n values: values.map(val => JSON.parse(val).v)\n };\n }\n /**\n * Merge data into the state database.\n */\n async _merge(contents) {\n await Promise.all(Object.keys(contents).map(key => contents[key] && this._save(key, contents[key])));\n }\n /**\n * Overwrite the entire database with new contents.\n */\n async _overwrite(contents) {\n await this._clear();\n await this._merge(contents);\n }\n /**\n * Remove a key in the database.\n */\n async _remove(id) {\n return this._connector.remove(id);\n }\n /**\n * Save a key and its value in the database.\n */\n async _save(id, value) {\n return this._connector.save(id, JSON.stringify({ v: value }));\n }\n}\nexports.StateDB = StateDB;\n/**\n * A namespace for StateDB statics.\n */\n(function (StateDB) {\n /**\n * An in-memory string key/value data connector.\n */\n class Connector {\n constructor() {\n this._storage = {};\n }\n /**\n * Retrieve an item from the data connector.\n */\n async fetch(id) {\n return this._storage[id];\n }\n /**\n * Retrieve the list of items available from the data connector.\n *\n * @param namespace - If not empty, only keys whose first token before `:`\n * exactly match `namespace` will be returned, e.g. `foo` in `foo:bar`.\n */\n async list(namespace = '') {\n return Object.keys(this._storage).reduce((acc, val) => {\n if (namespace === '' ? true : namespace === val.split(':')[0]) {\n acc.ids.push(val);\n acc.values.push(this._storage[val]);\n }\n return acc;\n }, { ids: [], values: [] });\n }\n /**\n * Remove a value using the data connector.\n */\n async remove(id) {\n delete this._storage[id];\n }\n /**\n * Save a value using the data connector.\n */\n async save(id, value) {\n this._storage[id] = value;\n }\n }\n StateDB.Connector = Connector;\n})(StateDB = exports.StateDB || (exports.StateDB = {}));\n//# sourceMappingURL=statedb.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IStateDB = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * The default state database token.\n */\nexports.IStateDB = new coreutils_1.Token('@jupyterlab/coreutils:IStateDB', `A service for the JupyterLab state database.\n Use this if you want to store data that will persist across page loads.\n See \"state database\" for more information.`);\n//# sourceMappingURL=tokens.js.map","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","import { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\n/**\n * A disposable object which delegates to a callback function.\n */\nclass DisposableDelegate {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn) {\n this._fn = fn;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return !this._fn;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n}\n/**\n * An observable disposable object which delegates to a callback function.\n */\nclass ObservableDisposableDelegate extends DisposableDelegate {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * An object which manages a collection of disposable items.\n */\nclass DisposableSet {\n constructor() {\n this._isDisposed = false;\n this._items = new Set();\n }\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item) {\n return this._items.has(item);\n }\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item) {\n this._items.add(item);\n }\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item) {\n this._items.delete(item);\n }\n /**\n * Remove all items from the set.\n */\n clear() {\n this._items.clear();\n }\n}\n/**\n * The namespace for the `DisposableSet` class statics.\n */\n(function (DisposableSet) {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n DisposableSet.from = from;\n})(DisposableSet || (DisposableSet = {}));\n/**\n * An observable object which manages a collection of disposable items.\n */\nclass ObservableDisposableSet extends DisposableSet {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\n(function (ObservableDisposableSet) {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n ObservableDisposableSet.from = from;\n})(ObservableDisposableSet || (ObservableDisposableSet = {}));\n\nexport { DisposableDelegate, DisposableSet, ObservableDisposableDelegate, ObservableDisposableSet };\n//# sourceMappingURL=index.es6.js.map\n","import { PromiseDelegate, JSONExt } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A class that wraps an asynchronous function to poll at a regular interval\n * with exponential increases to the interval length if the poll fails.\n *\n * @typeparam T - The resolved type of the factory's promises.\n * Defaults to `any`.\n *\n * @typeparam U - The rejected type of the factory's promises.\n * Defaults to `any`.\n *\n * @typeparam V - An optional type to extend the phases supported by a poll.\n * Defaults to `standby`, which already exists in the `Phase` type.\n */\nclass Poll {\n /**\n * Instantiate a new poll with exponential backoff in case of failure.\n *\n * @param options - The poll instantiation options.\n */\n constructor(options) {\n var _a;\n this._disposed = new Signal(this);\n this._lingered = 0;\n this._tick = new PromiseDelegate();\n this._ticked = new Signal(this);\n this._factory = options.factory;\n this._linger = (_a = options.linger) !== null && _a !== void 0 ? _a : Private.DEFAULT_LINGER;\n this._standby = options.standby || Private.DEFAULT_STANDBY;\n this._state = { ...Private.DEFAULT_STATE, timestamp: new Date().getTime() };\n // Normalize poll frequency `max` to be the greater of\n // default `max`, `options.frequency.max`, or `options.frequency.interval`.\n const frequency = options.frequency || {};\n const max = Math.max(frequency.interval || 0, frequency.max || 0, Private.DEFAULT_FREQUENCY.max);\n this.frequency = { ...Private.DEFAULT_FREQUENCY, ...frequency, ...{ max } };\n this.name = options.name || Private.DEFAULT_NAME;\n if ('auto' in options ? options.auto : true) {\n setTimeout(() => this.start());\n }\n }\n /**\n * A signal emitted when the poll is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * The polling frequency parameters.\n */\n get frequency() {\n return this._frequency;\n }\n set frequency(frequency) {\n if (this.isDisposed || JSONExt.deepEqual(frequency, this.frequency || {})) {\n return;\n }\n let { backoff, interval, max } = frequency;\n interval = Math.round(interval);\n max = Math.round(max);\n if (typeof backoff === 'number' && backoff < 1) {\n throw new Error('Poll backoff growth factor must be at least 1');\n }\n if ((interval < 0 || interval > max) && interval !== Poll.NEVER) {\n throw new Error('Poll interval must be between 0 and max');\n }\n if (max > Poll.MAX_INTERVAL && max !== Poll.NEVER) {\n throw new Error(`Max interval must be less than ${Poll.MAX_INTERVAL}`);\n }\n this._frequency = { backoff, interval, max };\n }\n /**\n * Whether the poll is disposed.\n */\n get isDisposed() {\n return this.state.phase === 'disposed';\n }\n /**\n * Indicates when the poll switches to standby.\n */\n get standby() {\n return this._standby;\n }\n set standby(standby) {\n if (this.isDisposed || this.standby === standby) {\n return;\n }\n this._standby = standby;\n }\n /**\n * The poll state, which is the content of the current poll tick.\n */\n get state() {\n return this._state;\n }\n /**\n * A promise that resolves when the poll next ticks.\n */\n get tick() {\n return this._tick.promise;\n }\n /**\n * A signal emitted when the poll ticks and fires off a new request.\n */\n get ticked() {\n return this._ticked;\n }\n /**\n * Return an async iterator that yields every tick.\n */\n async *[Symbol.asyncIterator]() {\n while (!this.isDisposed) {\n yield this.state;\n await this.tick.catch(() => undefined);\n }\n }\n /**\n * Dispose the poll.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._state = {\n ...Private.DISPOSED_STATE,\n timestamp: new Date().getTime()\n };\n this._tick.promise.catch(_ => undefined);\n this._tick.reject(new Error(`Poll (${this.name}) is disposed.`));\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n /**\n * Refreshes the poll. Schedules `refreshed` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n *\n * #### Notes\n * The returned promise resolves after the tick is scheduled, but before\n * the polling action is run. To wait until after the poll action executes,\n * await the `poll.tick` promise: `await poll.refresh(); await poll.tick;`\n */\n refresh() {\n return this.schedule({\n cancel: ({ phase }) => phase === 'refreshed',\n interval: Poll.IMMEDIATE,\n phase: 'refreshed'\n });\n }\n /**\n * Schedule the next poll tick.\n *\n * @param next - The next poll state data to schedule. Defaults to standby.\n *\n * @param next.cancel - Cancels state transition if function returns `true`.\n *\n * @returns A promise that resolves when the next poll state is active.\n *\n * #### Notes\n * This method is not meant to be invoked by user code typically. It is public\n * to allow poll instances to be composed into classes that schedule ticks.\n */\n async schedule(next = {}) {\n if (this.isDisposed) {\n return;\n }\n // Check if the phase transition should be canceled.\n if (next.cancel && next.cancel(this.state)) {\n return;\n }\n // Update poll state.\n const pending = this._tick;\n const scheduled = new PromiseDelegate();\n const state = {\n interval: this.frequency.interval,\n payload: null,\n phase: 'standby',\n timestamp: new Date().getTime(),\n ...next\n };\n this._state = state;\n this._tick = scheduled;\n // Clear the schedule if possible.\n clearTimeout(this._timeout);\n // Emit ticked signal, resolve pending promise, and await its settlement.\n this._ticked.emit(this.state);\n pending.resolve(this);\n await pending.promise;\n if (state.interval === Poll.NEVER) {\n this._timeout = undefined;\n return;\n }\n // Schedule next execution and cache its timeout handle.\n const execute = () => {\n if (this.isDisposed || this.tick !== scheduled.promise) {\n return;\n }\n this._execute();\n };\n // Cache the handle in case it needs to be unscheduled.\n this._timeout = setTimeout(execute, state.interval);\n }\n /**\n * Starts the poll. Schedules `started` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n */\n start() {\n return this.schedule({\n cancel: ({ phase }) => phase !== 'constructed' && phase !== 'standby' && phase !== 'stopped',\n interval: Poll.IMMEDIATE,\n phase: 'started'\n });\n }\n /**\n * Stops the poll. Schedules `stopped` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n */\n stop() {\n return this.schedule({\n cancel: ({ phase }) => phase === 'stopped',\n interval: Poll.NEVER,\n phase: 'stopped'\n });\n }\n /**\n * Whether the poll is hidden.\n *\n * #### Notes\n * This property is only relevant in a browser context.\n */\n get hidden() {\n return Private.hidden;\n }\n /**\n * Execute a new poll factory promise or stand by if necessary.\n */\n _execute() {\n let standby = typeof this.standby === 'function' ? this.standby() : this.standby;\n // Check if execution should proceed, linger, or stand by.\n if (standby === 'never') {\n standby = false;\n }\n else if (standby === 'when-hidden') {\n if (this.hidden) {\n standby = ++this._lingered > this._linger;\n }\n else {\n this._lingered = 0;\n standby = false;\n }\n }\n // If in standby mode schedule next tick without calling the factory.\n if (standby) {\n void this.schedule();\n return;\n }\n const pending = this.tick;\n this._factory(this.state)\n .then((resolved) => {\n if (this.isDisposed || this.tick !== pending) {\n return;\n }\n void this.schedule({\n payload: resolved,\n phase: this.state.phase === 'rejected' ? 'reconnected' : 'resolved'\n });\n })\n .catch((rejected) => {\n if (this.isDisposed || this.tick !== pending) {\n return;\n }\n void this.schedule({\n interval: Private.sleep(this.frequency, this.state),\n payload: rejected,\n phase: 'rejected'\n });\n });\n }\n}\n/**\n * A namespace for `Poll` types, interfaces, and statics.\n */\n(function (Poll) {\n /**\n * An interval value in ms that indicates the poll should tick immediately.\n */\n Poll.IMMEDIATE = 0;\n /**\n * Delays are 32-bit integers in many browsers so intervals need to be capped.\n *\n * #### Notes\n * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value\n */\n Poll.MAX_INTERVAL = 2147483647;\n /**\n * An interval value that indicates the poll should never tick.\n */\n Poll.NEVER = Infinity;\n})(Poll || (Poll = {}));\n/**\n * A namespace for private module data.\n */\nvar Private;\n(function (Private) {\n /**\n * The default backoff growth rate if `backoff` is `true`.\n */\n Private.DEFAULT_BACKOFF = 3;\n /**\n * The default polling frequency.\n */\n Private.DEFAULT_FREQUENCY = {\n backoff: true,\n interval: 1000,\n max: 30 * 1000\n };\n /**\n * The default number of times to `linger` when a poll is hidden.\n */\n Private.DEFAULT_LINGER = 1;\n /**\n * The default poll name.\n */\n Private.DEFAULT_NAME = 'unknown';\n /**\n * The default poll standby behavior.\n */\n Private.DEFAULT_STANDBY = 'when-hidden';\n /**\n * The first poll tick state's default values superseded in constructor.\n */\n Private.DEFAULT_STATE = {\n interval: Poll.NEVER,\n payload: null,\n phase: 'constructed',\n timestamp: new Date(0).getTime()\n };\n /**\n * The disposed tick state values.\n */\n Private.DISPOSED_STATE = {\n interval: Poll.NEVER,\n payload: null,\n phase: 'disposed',\n timestamp: new Date(0).getTime()\n };\n /**\n * Returns the number of milliseconds to sleep before the next tick.\n *\n * @param frequency - The poll's base frequency.\n * @param last - The poll's last tick.\n */\n function sleep(frequency, last) {\n const { backoff, interval, max } = frequency;\n if (interval === Poll.NEVER) {\n return interval;\n }\n const growth = backoff === true ? Private.DEFAULT_BACKOFF : backoff === false ? 1 : backoff;\n const random = getRandomIntInclusive(interval, last.interval * growth);\n return Math.min(max, random);\n }\n Private.sleep = sleep;\n /**\n * Keep track of whether the document is hidden. This flag is only relevant in\n * a browser context.\n *\n * Listen to `visibilitychange` event to set the `hidden` flag.\n *\n * Listening to `pagehide` is also necessary because Safari support for\n * `visibilitychange` events is partial, cf.\n * https://developer.mozilla.org/docs/Web/API/Document/visibilitychange_event\n */\n Private.hidden = (() => {\n if (typeof document === 'undefined') {\n return false;\n }\n document.addEventListener('visibilitychange', () => {\n Private.hidden = document.visibilityState === 'hidden';\n });\n document.addEventListener('pagehide', () => {\n Private.hidden = document.visibilityState === 'hidden';\n });\n return document.visibilityState === 'hidden';\n })();\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A base class to implement rate limiters with different invocation strategies.\n *\n * @typeparam T - The resolved type of the underlying function.\n *\n * @typeparam U - The rejected type of the underlying function.\n *\n * @typeparam V - Arguments for the underlying function.\n */\nclass RateLimiter {\n /**\n * Instantiate a rate limiter.\n *\n * @param fn - The function to rate limit.\n *\n * @param limit - The rate limit; defaults to 500ms.\n */\n constructor(fn, limit = 500) {\n /**\n * Arguments for the underlying function.\n */\n this.args = undefined;\n /**\n * A promise that resolves on each successful invocation.\n */\n this.payload = null;\n this.limit = limit;\n this.poll = new Poll({\n auto: false,\n factory: async () => {\n const { args } = this;\n this.args = undefined;\n return fn(...args);\n },\n frequency: { backoff: false, interval: Poll.NEVER, max: Poll.NEVER },\n standby: 'never'\n });\n this.payload = new PromiseDelegate();\n this.poll.ticked.connect((_, state) => {\n const { payload } = this;\n if (state.phase === 'resolved') {\n this.payload = new PromiseDelegate();\n payload.resolve(state.payload);\n return;\n }\n if (state.phase === 'rejected' || state.phase === 'stopped') {\n this.payload = new PromiseDelegate();\n payload.promise.catch(_ => undefined);\n payload.reject(state.payload);\n return;\n }\n }, this);\n }\n /**\n * Whether the rate limiter is disposed.\n */\n get isDisposed() {\n return this.payload === null;\n }\n /**\n * Disposes the rate limiter.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this.args = undefined;\n this.payload = null;\n this.poll.dispose();\n }\n /**\n * Stop the function if it is mid-flight.\n */\n async stop() {\n return this.poll.stop();\n }\n}\n/**\n * Wraps and debounces a function that can be called multiple times and only\n * executes the underlying function one `interval` after the last invocation.\n *\n * @typeparam T - The resolved type of the underlying function. Defaults to any.\n *\n * @typeparam U - The rejected type of the underlying function. Defaults to any.\n *\n * @typeparam V - Arguments for the underlying function. Defaults to any[].\n */\nclass Debouncer extends RateLimiter {\n /**\n * Invokes the function and only executes after rate limit has elapsed.\n * Each invocation resets the timer.\n */\n invoke(...args) {\n this.args = args;\n void this.poll.schedule({ interval: this.limit, phase: 'invoked' });\n return this.payload.promise;\n }\n}\n/**\n * Wraps and throttles a function that can be called multiple times and only\n * executes the underlying function once per `interval`.\n *\n * @typeparam T - The resolved type of the underlying function. Defaults to any.\n *\n * @typeparam U - The rejected type of the underlying function. Defaults to any.\n *\n * @typeparam V - Arguments for the underlying function. Defaults to any[].\n */\nclass Throttler extends RateLimiter {\n /**\n * Instantiate a throttler.\n *\n * @param fn - The function being throttled.\n *\n * @param options - Throttling configuration or throttling limit in ms.\n *\n * #### Notes\n * The `edge` defaults to `leading`; the `limit` defaults to `500`.\n */\n constructor(fn, options) {\n super(fn, typeof options === 'number' ? options : options && options.limit);\n this._trailing = false;\n if (typeof options !== 'number' && options && options.edge === 'trailing') {\n this._trailing = true;\n }\n this._interval = this._trailing ? this.limit : Poll.IMMEDIATE;\n }\n /**\n * Throttles function invocations if one is currently in flight.\n */\n invoke(...args) {\n const idle = this.poll.state.phase !== 'invoked';\n if (idle || this._trailing) {\n this.args = args;\n }\n if (idle) {\n void this.poll.schedule({ interval: this._interval, phase: 'invoked' });\n }\n return this.payload.promise;\n }\n}\n\nexport { Debouncer, Poll, RateLimiter, Throttler };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module properties\n */\n/**\n * A class which attaches a value to an external object.\n *\n * #### Notes\n * Attached properties are used to extend the state of an object with\n * semantic data from an unrelated class. They also encapsulate value\n * creation, coercion, and notification.\n *\n * Because attached property values are stored in a hash table, which\n * in turn is stored in a WeakMap keyed on the owner object, there is\n * non-trivial storage overhead involved in their use. The pattern is\n * therefore best used for the storage of rare data.\n */\nclass AttachedProperty {\n /**\n * Construct a new attached property.\n *\n * @param options - The options for initializing the property.\n */\n constructor(options) {\n this._pid = Private.nextPID();\n this.name = options.name;\n this._create = options.create;\n this._coerce = options.coerce || null;\n this._compare = options.compare || null;\n this._changed = options.changed || null;\n }\n /**\n * Get the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @returns The current value of the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and assigned as the current value of the property.\n */\n get(owner) {\n let value;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n value = map[this._pid];\n }\n else {\n value = map[this._pid] = this._createValue(owner);\n }\n return value;\n }\n /**\n * Set the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @param value - The value for the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n set(owner, value) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, value);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Explicitly coerce the current property value for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n coerce(owner) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, oldValue);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Get or create the default value for the given owner.\n */\n _createValue(owner) {\n let create = this._create;\n return create(owner);\n }\n /**\n * Coerce the value for the given owner.\n */\n _coerceValue(owner, value) {\n let coerce = this._coerce;\n return coerce ? coerce(owner, value) : value;\n }\n /**\n * Compare the old value and new value for equality.\n */\n _compareValue(oldValue, newValue) {\n let compare = this._compare;\n return compare ? compare(oldValue, newValue) : oldValue === newValue;\n }\n /**\n * Run the change notification if the given values are different.\n */\n _maybeNotify(owner, oldValue, newValue) {\n let changed = this._changed;\n if (changed && !this._compareValue(oldValue, newValue)) {\n changed(owner, oldValue, newValue);\n }\n }\n}\n/**\n * The namespace for the `AttachedProperty` class statics.\n */\n(function (AttachedProperty) {\n /**\n * Clear the stored property data for the given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * This will clear all property values for the owner, but it will\n * **not** run the change notification for any of the properties.\n */\n function clearData(owner) {\n Private.ownerData.delete(owner);\n }\n AttachedProperty.clearData = clearData;\n})(AttachedProperty || (AttachedProperty = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A weak mapping of property owner to property map.\n */\n Private.ownerData = new WeakMap();\n /**\n * A function which computes successive unique property ids.\n */\n Private.nextPID = (() => {\n let id = 0;\n return () => {\n let rand = Math.random();\n let stem = `${rand}`.slice(2);\n return `pid-${stem}-${id++}`;\n };\n })();\n /**\n * Lookup the data map for the property owner.\n *\n * This will create the map if one does not already exist.\n */\n function ensureMap(owner) {\n let map = Private.ownerData.get(owner);\n if (map) {\n return map;\n }\n map = Object.create(null);\n Private.ownerData.set(owner, map);\n return map;\n }\n Private.ensureMap = ensureMap;\n})(Private || (Private = {}));\n\nexport { AttachedProperty };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nfunction* chain(...objects) {\n for (const object of objects) {\n yield* object;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nfunction* empty() {\n return;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nfunction* enumerate(object, start = 0) {\n for (const value of object) {\n yield [start++, value];\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* filter(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nfunction find(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nfunction findIndex(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nfunction min(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nfunction max(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nfunction minmax(object, fn) {\n let empty = true;\n let vmin;\n let vmax;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n }\n else if (fn(value, vmin) < 0) {\n vmin = value;\n }\n else if (fn(value, vmax) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin, vmax];\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nfunction toArray(object) {\n return Array.from(object);\n}\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nfunction toObject(object) {\n const result = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nfunction each(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nfunction every(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nfunction some(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* map(object, fn) {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nfunction* range(start, stop, step) {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n }\n else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nfunction reduce(object, fn, initial) {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n // Setup the initial accumlated value.\n let accumulator;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n }\n else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n // Iterate the rest of the values, updating the accumulator.\n let next;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n // Return the final accumulated value.\n return accumulator;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nfunction* repeat(value, count) {\n while (0 < count--) {\n yield value;\n }\n}\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nfunction* once(value) {\n yield value;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nfunction* retro(object) {\n if (typeof object.retro === 'function') {\n yield* object.retro();\n }\n else {\n for (let index = object.length - 1; index > -1; index--) {\n yield object[index];\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nfunction* stride(object, step) {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nfunction* take(object, count) {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nfunction* zip(...objects) {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n\nexport { ArrayExt, StringExt, chain, each, empty, enumerate, every, filter, find, findIndex, map, max, min, minmax, once, range, reduce, repeat, retro, some, stride, take, toArray, toObject, topologicSort, zip };\n//# sourceMappingURL=index.es6.js.map\n","import { find, ArrayExt } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nclass Signal {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender) {\n this.sender = sender;\n }\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot, thisArg) {\n return Private.connect(this, slot, thisArg);\n }\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot, thisArg) {\n return Private.disconnect(this, slot, thisArg);\n }\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args) {\n Private.emit(this, args);\n }\n}\n/**\n * The namespace for the `Signal` class statics.\n */\n(function (Signal) {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectBetween(sender, receiver) {\n Private.disconnectBetween(sender, receiver);\n }\n Signal.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n Private.disconnectSender(sender);\n }\n Signal.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectReceiver(receiver) {\n Private.disconnectReceiver(receiver);\n }\n Signal.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectAll(object) {\n Private.disconnectAll(object);\n }\n Signal.disconnectAll = disconnectAll;\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n function clearData(object) {\n Private.disconnectAll(object);\n }\n Signal.clearData = clearData;\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return Private.exceptionHandler;\n }\n Signal.getExceptionHandler = getExceptionHandler;\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n Signal.setExceptionHandler = setExceptionHandler;\n})(Signal || (Signal = {}));\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nclass Stream extends Signal {\n constructor() {\n super(...arguments);\n this._pending = new PromiseDelegate();\n }\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator]() {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n }\n catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args) {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n /**\n * Stop the stream's async iteration.\n */\n stop() {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The signal exception handler function.\n */\n Private.exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n function connect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n // Indicate a successful connection.\n return true;\n }\n Private.connect = connect;\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n function disconnect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver);\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n // Indicate a successful disconnection.\n return true;\n }\n Private.disconnect = disconnect;\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectBetween(sender, receiver) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n Private.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver));\n }\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n Private.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectReceiver(receiver) {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender));\n }\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n Private.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n function disconnectAll(object) {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n Private.disconnectAll = disconnectAll;\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n function emit(signal, args) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n Private.emit = emit;\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap();\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap();\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(connections, signal, slot, thisArg) {\n return find(connections, connection => connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg);\n }\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection, args) {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal.sender, args);\n }\n catch (err) {\n Private.exceptionHandler(err);\n }\n }\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection) {\n return connection.signal === null;\n }\n})(Private || (Private = {}));\n\nexport { Signal, Stream };\n//# sourceMappingURL=index.es6.js.map\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.JSON5 = factory());\n}(this, (function () { 'use strict';\n\n\tfunction createCommonjsModule(fn, module) {\n\t\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n\t}\n\n\tvar _global = createCommonjsModule(function (module) {\n\t// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\n\tvar global = module.exports = typeof window != 'undefined' && window.Math == Math\n\t ? window : typeof self != 'undefined' && self.Math == Math ? self\n\t // eslint-disable-next-line no-new-func\n\t : Function('return this')();\n\tif (typeof __g == 'number') { __g = global; } // eslint-disable-line no-undef\n\t});\n\n\tvar _core = createCommonjsModule(function (module) {\n\tvar core = module.exports = { version: '2.6.5' };\n\tif (typeof __e == 'number') { __e = core; } // eslint-disable-line no-undef\n\t});\n\tvar _core_1 = _core.version;\n\n\tvar _isObject = function (it) {\n\t return typeof it === 'object' ? it !== null : typeof it === 'function';\n\t};\n\n\tvar _anObject = function (it) {\n\t if (!_isObject(it)) { throw TypeError(it + ' is not an object!'); }\n\t return it;\n\t};\n\n\tvar _fails = function (exec) {\n\t try {\n\t return !!exec();\n\t } catch (e) {\n\t return true;\n\t }\n\t};\n\n\t// Thank's IE8 for his funny defineProperty\n\tvar _descriptors = !_fails(function () {\n\t return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;\n\t});\n\n\tvar document = _global.document;\n\t// typeof document.createElement is 'object' in old IE\n\tvar is = _isObject(document) && _isObject(document.createElement);\n\tvar _domCreate = function (it) {\n\t return is ? document.createElement(it) : {};\n\t};\n\n\tvar _ie8DomDefine = !_descriptors && !_fails(function () {\n\t return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7;\n\t});\n\n\t// 7.1.1 ToPrimitive(input [, PreferredType])\n\n\t// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n\t// and the second argument - flag - preferred type is a string\n\tvar _toPrimitive = function (it, S) {\n\t if (!_isObject(it)) { return it; }\n\t var fn, val;\n\t if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; }\n\t if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) { return val; }\n\t if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; }\n\t throw TypeError(\"Can't convert object to primitive value\");\n\t};\n\n\tvar dP = Object.defineProperty;\n\n\tvar f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) {\n\t _anObject(O);\n\t P = _toPrimitive(P, true);\n\t _anObject(Attributes);\n\t if (_ie8DomDefine) { try {\n\t return dP(O, P, Attributes);\n\t } catch (e) { /* empty */ } }\n\t if ('get' in Attributes || 'set' in Attributes) { throw TypeError('Accessors not supported!'); }\n\t if ('value' in Attributes) { O[P] = Attributes.value; }\n\t return O;\n\t};\n\n\tvar _objectDp = {\n\t\tf: f\n\t};\n\n\tvar _propertyDesc = function (bitmap, value) {\n\t return {\n\t enumerable: !(bitmap & 1),\n\t configurable: !(bitmap & 2),\n\t writable: !(bitmap & 4),\n\t value: value\n\t };\n\t};\n\n\tvar _hide = _descriptors ? function (object, key, value) {\n\t return _objectDp.f(object, key, _propertyDesc(1, value));\n\t} : function (object, key, value) {\n\t object[key] = value;\n\t return object;\n\t};\n\n\tvar hasOwnProperty = {}.hasOwnProperty;\n\tvar _has = function (it, key) {\n\t return hasOwnProperty.call(it, key);\n\t};\n\n\tvar id = 0;\n\tvar px = Math.random();\n\tvar _uid = function (key) {\n\t return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n\t};\n\n\tvar _library = false;\n\n\tvar _shared = createCommonjsModule(function (module) {\n\tvar SHARED = '__core-js_shared__';\n\tvar store = _global[SHARED] || (_global[SHARED] = {});\n\n\t(module.exports = function (key, value) {\n\t return store[key] || (store[key] = value !== undefined ? value : {});\n\t})('versions', []).push({\n\t version: _core.version,\n\t mode: _library ? 'pure' : 'global',\n\t copyright: '© 2019 Denis Pushkarev (zloirock.ru)'\n\t});\n\t});\n\n\tvar _functionToString = _shared('native-function-to-string', Function.toString);\n\n\tvar _redefine = createCommonjsModule(function (module) {\n\tvar SRC = _uid('src');\n\n\tvar TO_STRING = 'toString';\n\tvar TPL = ('' + _functionToString).split(TO_STRING);\n\n\t_core.inspectSource = function (it) {\n\t return _functionToString.call(it);\n\t};\n\n\t(module.exports = function (O, key, val, safe) {\n\t var isFunction = typeof val == 'function';\n\t if (isFunction) { _has(val, 'name') || _hide(val, 'name', key); }\n\t if (O[key] === val) { return; }\n\t if (isFunction) { _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); }\n\t if (O === _global) {\n\t O[key] = val;\n\t } else if (!safe) {\n\t delete O[key];\n\t _hide(O, key, val);\n\t } else if (O[key]) {\n\t O[key] = val;\n\t } else {\n\t _hide(O, key, val);\n\t }\n\t// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n\t})(Function.prototype, TO_STRING, function toString() {\n\t return typeof this == 'function' && this[SRC] || _functionToString.call(this);\n\t});\n\t});\n\n\tvar _aFunction = function (it) {\n\t if (typeof it != 'function') { throw TypeError(it + ' is not a function!'); }\n\t return it;\n\t};\n\n\t// optional / simple context binding\n\n\tvar _ctx = function (fn, that, length) {\n\t _aFunction(fn);\n\t if (that === undefined) { return fn; }\n\t switch (length) {\n\t case 1: return function (a) {\n\t return fn.call(that, a);\n\t };\n\t case 2: return function (a, b) {\n\t return fn.call(that, a, b);\n\t };\n\t case 3: return function (a, b, c) {\n\t return fn.call(that, a, b, c);\n\t };\n\t }\n\t return function (/* ...args */) {\n\t return fn.apply(that, arguments);\n\t };\n\t};\n\n\tvar PROTOTYPE = 'prototype';\n\n\tvar $export = function (type, name, source) {\n\t var IS_FORCED = type & $export.F;\n\t var IS_GLOBAL = type & $export.G;\n\t var IS_STATIC = type & $export.S;\n\t var IS_PROTO = type & $export.P;\n\t var IS_BIND = type & $export.B;\n\t var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE];\n\t var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {});\n\t var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});\n\t var key, own, out, exp;\n\t if (IS_GLOBAL) { source = name; }\n\t for (key in source) {\n\t // contains in native\n\t own = !IS_FORCED && target && target[key] !== undefined;\n\t // export native or passed\n\t out = (own ? target : source)[key];\n\t // bind timers to global for call from export context\n\t exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out;\n\t // extend global\n\t if (target) { _redefine(target, key, out, type & $export.U); }\n\t // export\n\t if (exports[key] != out) { _hide(exports, key, exp); }\n\t if (IS_PROTO && expProto[key] != out) { expProto[key] = out; }\n\t }\n\t};\n\t_global.core = _core;\n\t// type bitmap\n\t$export.F = 1; // forced\n\t$export.G = 2; // global\n\t$export.S = 4; // static\n\t$export.P = 8; // proto\n\t$export.B = 16; // bind\n\t$export.W = 32; // wrap\n\t$export.U = 64; // safe\n\t$export.R = 128; // real proto method for `library`\n\tvar _export = $export;\n\n\t// 7.1.4 ToInteger\n\tvar ceil = Math.ceil;\n\tvar floor = Math.floor;\n\tvar _toInteger = function (it) {\n\t return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n\t};\n\n\t// 7.2.1 RequireObjectCoercible(argument)\n\tvar _defined = function (it) {\n\t if (it == undefined) { throw TypeError(\"Can't call method on \" + it); }\n\t return it;\n\t};\n\n\t// true -> String#at\n\t// false -> String#codePointAt\n\tvar _stringAt = function (TO_STRING) {\n\t return function (that, pos) {\n\t var s = String(_defined(that));\n\t var i = _toInteger(pos);\n\t var l = s.length;\n\t var a, b;\n\t if (i < 0 || i >= l) { return TO_STRING ? '' : undefined; }\n\t a = s.charCodeAt(i);\n\t return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff\n\t ? TO_STRING ? s.charAt(i) : a\n\t : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;\n\t };\n\t};\n\n\tvar $at = _stringAt(false);\n\t_export(_export.P, 'String', {\n\t // 21.1.3.3 String.prototype.codePointAt(pos)\n\t codePointAt: function codePointAt(pos) {\n\t return $at(this, pos);\n\t }\n\t});\n\n\tvar codePointAt = _core.String.codePointAt;\n\n\tvar max = Math.max;\n\tvar min = Math.min;\n\tvar _toAbsoluteIndex = function (index, length) {\n\t index = _toInteger(index);\n\t return index < 0 ? max(index + length, 0) : min(index, length);\n\t};\n\n\tvar fromCharCode = String.fromCharCode;\n\tvar $fromCodePoint = String.fromCodePoint;\n\n\t// length should be 1, old FF problem\n\t_export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {\n\t // 21.1.2.2 String.fromCodePoint(...codePoints)\n\t fromCodePoint: function fromCodePoint(x) {\n\t var arguments$1 = arguments;\n\t // eslint-disable-line no-unused-vars\n\t var res = [];\n\t var aLen = arguments.length;\n\t var i = 0;\n\t var code;\n\t while (aLen > i) {\n\t code = +arguments$1[i++];\n\t if (_toAbsoluteIndex(code, 0x10ffff) !== code) { throw RangeError(code + ' is not a valid code point'); }\n\t res.push(code < 0x10000\n\t ? fromCharCode(code)\n\t : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)\n\t );\n\t } return res.join('');\n\t }\n\t});\n\n\tvar fromCodePoint = _core.String.fromCodePoint;\n\n\t// This is a generated file. Do not edit.\n\tvar Space_Separator = /[\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/;\n\tvar ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\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uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\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DE1D]/;\n\tvar ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09FC\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0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BD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\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36-\\uDD3F\\uDD50-\\uDD73\\uDD76\\uDD80-\\uDDC4\\uDDCA-\\uDDCC\\uDDD0-\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE37\\uDE3E\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF00-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3C-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF50\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC00-\\uDC4A\\uDC50-\\uDC59\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDDD8-\\uDDDD\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9\\uDF00-\\uDF19\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDCA0-\\uDCE9\\uDCFF\\uDE00-\\uDE3E\\uDE47\\uDE50-\\uDE83\\uDE86-\\uDE99\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\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DC00-\\uDC06\\uDC08-\\uDC18\\uDC1B-\\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A]|\\uD83A[\\uDC00-\\uDCC4\\uDCD0-\\uDCD6\\uDD00-\\uDD4A\\uDD50-\\uDD59]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/;\n\n\tvar unicode = {\n\t\tSpace_Separator: Space_Separator,\n\t\tID_Start: ID_Start,\n\t\tID_Continue: ID_Continue\n\t};\n\n\tvar util = {\n\t isSpaceSeparator: function isSpaceSeparator (c) {\n\t return typeof c === 'string' && unicode.Space_Separator.test(c)\n\t },\n\n\t isIdStartChar: function isIdStartChar (c) {\n\t return typeof c === 'string' && (\n\t (c >= 'a' && c <= 'z') ||\n\t (c >= 'A' && c <= 'Z') ||\n\t (c === '$') || (c === '_') ||\n\t unicode.ID_Start.test(c)\n\t )\n\t },\n\n\t isIdContinueChar: function isIdContinueChar (c) {\n\t return typeof c === 'string' && (\n\t (c >= 'a' && c <= 'z') ||\n\t (c >= 'A' && c <= 'Z') ||\n\t (c >= '0' && c <= '9') ||\n\t (c === '$') || (c === '_') ||\n\t (c === '\\u200C') || (c === '\\u200D') ||\n\t unicode.ID_Continue.test(c)\n\t )\n\t },\n\n\t isDigit: function isDigit (c) {\n\t return typeof c === 'string' && /[0-9]/.test(c)\n\t },\n\n\t isHexDigit: function isHexDigit (c) {\n\t return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)\n\t },\n\t};\n\n\tvar source;\n\tvar parseState;\n\tvar stack;\n\tvar pos;\n\tvar line;\n\tvar column;\n\tvar token;\n\tvar key;\n\tvar root;\n\n\tvar parse = function parse (text, reviver) {\n\t source = String(text);\n\t parseState = 'start';\n\t stack = [];\n\t pos = 0;\n\t line = 1;\n\t column = 0;\n\t token = undefined;\n\t key = undefined;\n\t root = undefined;\n\n\t do {\n\t token = lex();\n\n\t // This code is unreachable.\n\t // if (!parseStates[parseState]) {\n\t // throw invalidParseState()\n\t // }\n\n\t parseStates[parseState]();\n\t } while (token.type !== 'eof')\n\n\t if (typeof reviver === 'function') {\n\t return internalize({'': root}, '', reviver)\n\t }\n\n\t return root\n\t};\n\n\tfunction internalize (holder, name, reviver) {\n\t var value = holder[name];\n\t if (value != null && typeof value === 'object') {\n\t if (Array.isArray(value)) {\n\t for (var i = 0; i < value.length; i++) {\n\t var key = String(i);\n\t var replacement = internalize(value, key, reviver);\n\t if (replacement === undefined) {\n\t delete value[key];\n\t } else {\n\t Object.defineProperty(value, key, {\n\t value: replacement,\n\t writable: true,\n\t enumerable: true,\n\t configurable: true,\n\t });\n\t }\n\t }\n\t } else {\n\t for (var key$1 in value) {\n\t var replacement$1 = internalize(value, key$1, reviver);\n\t if (replacement$1 === undefined) {\n\t delete value[key$1];\n\t } else {\n\t Object.defineProperty(value, key$1, {\n\t value: replacement$1,\n\t writable: true,\n\t enumerable: true,\n\t configurable: true,\n\t });\n\t }\n\t }\n\t }\n\t }\n\n\t return reviver.call(holder, name, value)\n\t}\n\n\tvar lexState;\n\tvar buffer;\n\tvar doubleQuote;\n\tvar sign;\n\tvar c;\n\n\tfunction lex () {\n\t lexState = 'default';\n\t buffer = '';\n\t doubleQuote = false;\n\t sign = 1;\n\n\t for (;;) {\n\t c = peek();\n\n\t // This code is unreachable.\n\t // if (!lexStates[lexState]) {\n\t // throw invalidLexState(lexState)\n\t // }\n\n\t var token = lexStates[lexState]();\n\t if (token) {\n\t return token\n\t }\n\t }\n\t}\n\n\tfunction peek () {\n\t if (source[pos]) {\n\t return String.fromCodePoint(source.codePointAt(pos))\n\t }\n\t}\n\n\tfunction read () {\n\t var c = peek();\n\n\t if (c === '\\n') {\n\t line++;\n\t column = 0;\n\t } else if (c) {\n\t column += c.length;\n\t } else {\n\t column++;\n\t }\n\n\t if (c) {\n\t pos += c.length;\n\t }\n\n\t return c\n\t}\n\n\tvar lexStates = {\n\t default: function default$1 () {\n\t switch (c) {\n\t case '\\t':\n\t case '\\v':\n\t case '\\f':\n\t case ' ':\n\t case '\\u00A0':\n\t case '\\uFEFF':\n\t case '\\n':\n\t case '\\r':\n\t case '\\u2028':\n\t case '\\u2029':\n\t read();\n\t return\n\n\t case '/':\n\t read();\n\t lexState = 'comment';\n\t return\n\n\t case undefined:\n\t read();\n\t return newToken('eof')\n\t }\n\n\t if (util.isSpaceSeparator(c)) {\n\t read();\n\t return\n\t }\n\n\t // This code is unreachable.\n\t // if (!lexStates[parseState]) {\n\t // throw invalidLexState(parseState)\n\t // }\n\n\t return lexStates[parseState]()\n\t },\n\n\t comment: function comment () {\n\t switch (c) {\n\t case '*':\n\t read();\n\t lexState = 'multiLineComment';\n\t return\n\n\t case '/':\n\t read();\n\t lexState = 'singleLineComment';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t multiLineComment: function multiLineComment () {\n\t switch (c) {\n\t case '*':\n\t read();\n\t lexState = 'multiLineCommentAsterisk';\n\t return\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t },\n\n\t multiLineCommentAsterisk: function multiLineCommentAsterisk () {\n\t switch (c) {\n\t case '*':\n\t read();\n\t return\n\n\t case '/':\n\t read();\n\t lexState = 'default';\n\t return\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t lexState = 'multiLineComment';\n\t },\n\n\t singleLineComment: function singleLineComment () {\n\t switch (c) {\n\t case '\\n':\n\t case '\\r':\n\t case '\\u2028':\n\t case '\\u2029':\n\t read();\n\t lexState = 'default';\n\t return\n\n\t case undefined:\n\t read();\n\t return newToken('eof')\n\t }\n\n\t read();\n\t },\n\n\t value: function value () {\n\t switch (c) {\n\t case '{':\n\t case '[':\n\t return newToken('punctuator', read())\n\n\t case 'n':\n\t read();\n\t literal('ull');\n\t return newToken('null', null)\n\n\t case 't':\n\t read();\n\t literal('rue');\n\t return newToken('boolean', true)\n\n\t case 'f':\n\t read();\n\t literal('alse');\n\t return newToken('boolean', false)\n\n\t case '-':\n\t case '+':\n\t if (read() === '-') {\n\t sign = -1;\n\t }\n\n\t lexState = 'sign';\n\t return\n\n\t case '.':\n\t buffer = read();\n\t lexState = 'decimalPointLeading';\n\t return\n\n\t case '0':\n\t buffer = read();\n\t lexState = 'zero';\n\t return\n\n\t case '1':\n\t case '2':\n\t case '3':\n\t case '4':\n\t case '5':\n\t case '6':\n\t case '7':\n\t case '8':\n\t case '9':\n\t buffer = read();\n\t lexState = 'decimalInteger';\n\t return\n\n\t case 'I':\n\t read();\n\t literal('nfinity');\n\t return newToken('numeric', Infinity)\n\n\t case 'N':\n\t read();\n\t literal('aN');\n\t return newToken('numeric', NaN)\n\n\t case '\"':\n\t case \"'\":\n\t doubleQuote = (read() === '\"');\n\t buffer = '';\n\t lexState = 'string';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t identifierNameStartEscape: function identifierNameStartEscape () {\n\t if (c !== 'u') {\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t var u = unicodeEscape();\n\t switch (u) {\n\t case '$':\n\t case '_':\n\t break\n\n\t default:\n\t if (!util.isIdStartChar(u)) {\n\t throw invalidIdentifier()\n\t }\n\n\t break\n\t }\n\n\t buffer += u;\n\t lexState = 'identifierName';\n\t },\n\n\t identifierName: function identifierName () {\n\t switch (c) {\n\t case '$':\n\t case '_':\n\t case '\\u200C':\n\t case '\\u200D':\n\t buffer += read();\n\t return\n\n\t case '\\\\':\n\t read();\n\t lexState = 'identifierNameEscape';\n\t return\n\t }\n\n\t if (util.isIdContinueChar(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('identifier', buffer)\n\t },\n\n\t identifierNameEscape: function identifierNameEscape () {\n\t if (c !== 'u') {\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t var u = unicodeEscape();\n\t switch (u) {\n\t case '$':\n\t case '_':\n\t case '\\u200C':\n\t case '\\u200D':\n\t break\n\n\t default:\n\t if (!util.isIdContinueChar(u)) {\n\t throw invalidIdentifier()\n\t }\n\n\t break\n\t }\n\n\t buffer += u;\n\t lexState = 'identifierName';\n\t },\n\n\t sign: function sign$1 () {\n\t switch (c) {\n\t case '.':\n\t buffer = read();\n\t lexState = 'decimalPointLeading';\n\t return\n\n\t case '0':\n\t buffer = read();\n\t lexState = 'zero';\n\t return\n\n\t case '1':\n\t case '2':\n\t case '3':\n\t case '4':\n\t case '5':\n\t case '6':\n\t case '7':\n\t case '8':\n\t case '9':\n\t buffer = read();\n\t lexState = 'decimalInteger';\n\t return\n\n\t case 'I':\n\t read();\n\t literal('nfinity');\n\t return newToken('numeric', sign * Infinity)\n\n\t case 'N':\n\t read();\n\t literal('aN');\n\t return newToken('numeric', NaN)\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t zero: function zero () {\n\t switch (c) {\n\t case '.':\n\t buffer += read();\n\t lexState = 'decimalPoint';\n\t return\n\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\n\t case 'x':\n\t case 'X':\n\t buffer += read();\n\t lexState = 'hexadecimal';\n\t return\n\t }\n\n\t return newToken('numeric', sign * 0)\n\t },\n\n\t decimalInteger: function decimalInteger () {\n\t switch (c) {\n\t case '.':\n\t buffer += read();\n\t lexState = 'decimalPoint';\n\t return\n\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t decimalPointLeading: function decimalPointLeading () {\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalFraction';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t decimalPoint: function decimalPoint () {\n\t switch (c) {\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalFraction';\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t decimalFraction: function decimalFraction () {\n\t switch (c) {\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t decimalExponent: function decimalExponent () {\n\t switch (c) {\n\t case '+':\n\t case '-':\n\t buffer += read();\n\t lexState = 'decimalExponentSign';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalExponentInteger';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t decimalExponentSign: function decimalExponentSign () {\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalExponentInteger';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t decimalExponentInteger: function decimalExponentInteger () {\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t hexadecimal: function hexadecimal () {\n\t if (util.isHexDigit(c)) {\n\t buffer += read();\n\t lexState = 'hexadecimalInteger';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t hexadecimalInteger: function hexadecimalInteger () {\n\t if (util.isHexDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t string: function string () {\n\t switch (c) {\n\t case '\\\\':\n\t read();\n\t buffer += escape();\n\t return\n\n\t case '\"':\n\t if (doubleQuote) {\n\t read();\n\t return newToken('string', buffer)\n\t }\n\n\t buffer += read();\n\t return\n\n\t case \"'\":\n\t if (!doubleQuote) {\n\t read();\n\t return newToken('string', buffer)\n\t }\n\n\t buffer += read();\n\t return\n\n\t case '\\n':\n\t case '\\r':\n\t throw invalidChar(read())\n\n\t case '\\u2028':\n\t case '\\u2029':\n\t separatorChar(c);\n\t break\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\t },\n\n\t start: function start () {\n\t switch (c) {\n\t case '{':\n\t case '[':\n\t return newToken('punctuator', read())\n\n\t // This code is unreachable since the default lexState handles eof.\n\t // case undefined:\n\t // return newToken('eof')\n\t }\n\n\t lexState = 'value';\n\t },\n\n\t beforePropertyName: function beforePropertyName () {\n\t switch (c) {\n\t case '$':\n\t case '_':\n\t buffer = read();\n\t lexState = 'identifierName';\n\t return\n\n\t case '\\\\':\n\t read();\n\t lexState = 'identifierNameStartEscape';\n\t return\n\n\t case '}':\n\t return newToken('punctuator', read())\n\n\t case '\"':\n\t case \"'\":\n\t doubleQuote = (read() === '\"');\n\t lexState = 'string';\n\t return\n\t }\n\n\t if (util.isIdStartChar(c)) {\n\t buffer += read();\n\t lexState = 'identifierName';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t afterPropertyName: function afterPropertyName () {\n\t if (c === ':') {\n\t return newToken('punctuator', read())\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t beforePropertyValue: function beforePropertyValue () {\n\t lexState = 'value';\n\t },\n\n\t afterPropertyValue: function afterPropertyValue () {\n\t switch (c) {\n\t case ',':\n\t case '}':\n\t return newToken('punctuator', read())\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t beforeArrayValue: function beforeArrayValue () {\n\t if (c === ']') {\n\t return newToken('punctuator', read())\n\t }\n\n\t lexState = 'value';\n\t },\n\n\t afterArrayValue: function afterArrayValue () {\n\t switch (c) {\n\t case ',':\n\t case ']':\n\t return newToken('punctuator', read())\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t end: function end () {\n\t // This code is unreachable since it's handled by the default lexState.\n\t // if (c === undefined) {\n\t // read()\n\t // return newToken('eof')\n\t // }\n\n\t throw invalidChar(read())\n\t },\n\t};\n\n\tfunction newToken (type, value) {\n\t return {\n\t type: type,\n\t value: value,\n\t line: line,\n\t column: column,\n\t }\n\t}\n\n\tfunction literal (s) {\n\t for (var i = 0, list = s; i < list.length; i += 1) {\n\t var c = list[i];\n\n\t var p = peek();\n\n\t if (p !== c) {\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t }\n\t}\n\n\tfunction escape () {\n\t var c = peek();\n\t switch (c) {\n\t case 'b':\n\t read();\n\t return '\\b'\n\n\t case 'f':\n\t read();\n\t return '\\f'\n\n\t case 'n':\n\t read();\n\t return '\\n'\n\n\t case 'r':\n\t read();\n\t return '\\r'\n\n\t case 't':\n\t read();\n\t return '\\t'\n\n\t case 'v':\n\t read();\n\t return '\\v'\n\n\t case '0':\n\t read();\n\t if (util.isDigit(peek())) {\n\t throw invalidChar(read())\n\t }\n\n\t return '\\0'\n\n\t case 'x':\n\t read();\n\t return hexEscape()\n\n\t case 'u':\n\t read();\n\t return unicodeEscape()\n\n\t case '\\n':\n\t case '\\u2028':\n\t case '\\u2029':\n\t read();\n\t return ''\n\n\t case '\\r':\n\t read();\n\t if (peek() === '\\n') {\n\t read();\n\t }\n\n\t return ''\n\n\t case '1':\n\t case '2':\n\t case '3':\n\t case '4':\n\t case '5':\n\t case '6':\n\t case '7':\n\t case '8':\n\t case '9':\n\t throw invalidChar(read())\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t return read()\n\t}\n\n\tfunction hexEscape () {\n\t var buffer = '';\n\t var c = peek();\n\n\t if (!util.isHexDigit(c)) {\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\n\t c = peek();\n\t if (!util.isHexDigit(c)) {\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\n\t return String.fromCodePoint(parseInt(buffer, 16))\n\t}\n\n\tfunction unicodeEscape () {\n\t var buffer = '';\n\t var count = 4;\n\n\t while (count-- > 0) {\n\t var c = peek();\n\t if (!util.isHexDigit(c)) {\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\t }\n\n\t return String.fromCodePoint(parseInt(buffer, 16))\n\t}\n\n\tvar parseStates = {\n\t start: function start () {\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t push();\n\t },\n\n\t beforePropertyName: function beforePropertyName () {\n\t switch (token.type) {\n\t case 'identifier':\n\t case 'string':\n\t key = token.value;\n\t parseState = 'afterPropertyName';\n\t return\n\n\t case 'punctuator':\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.value !== '}') {\n\t // throw invalidToken()\n\t // }\n\n\t pop();\n\t return\n\n\t case 'eof':\n\t throw invalidEOF()\n\t }\n\n\t // This code is unreachable since it's handled by the lexState.\n\t // throw invalidToken()\n\t },\n\n\t afterPropertyName: function afterPropertyName () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'punctuator' || token.value !== ':') {\n\t // throw invalidToken()\n\t // }\n\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t parseState = 'beforePropertyValue';\n\t },\n\n\t beforePropertyValue: function beforePropertyValue () {\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t push();\n\t },\n\n\t beforeArrayValue: function beforeArrayValue () {\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t if (token.type === 'punctuator' && token.value === ']') {\n\t pop();\n\t return\n\t }\n\n\t push();\n\t },\n\n\t afterPropertyValue: function afterPropertyValue () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'punctuator') {\n\t // throw invalidToken()\n\t // }\n\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t switch (token.value) {\n\t case ',':\n\t parseState = 'beforePropertyName';\n\t return\n\n\t case '}':\n\t pop();\n\t }\n\n\t // This code is unreachable since it's handled by the lexState.\n\t // throw invalidToken()\n\t },\n\n\t afterArrayValue: function afterArrayValue () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'punctuator') {\n\t // throw invalidToken()\n\t // }\n\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t switch (token.value) {\n\t case ',':\n\t parseState = 'beforeArrayValue';\n\t return\n\n\t case ']':\n\t pop();\n\t }\n\n\t // This code is unreachable since it's handled by the lexState.\n\t // throw invalidToken()\n\t },\n\n\t end: function end () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'eof') {\n\t // throw invalidToken()\n\t // }\n\t },\n\t};\n\n\tfunction push () {\n\t var value;\n\n\t switch (token.type) {\n\t case 'punctuator':\n\t switch (token.value) {\n\t case '{':\n\t value = {};\n\t break\n\n\t case '[':\n\t value = [];\n\t break\n\t }\n\n\t break\n\n\t case 'null':\n\t case 'boolean':\n\t case 'numeric':\n\t case 'string':\n\t value = token.value;\n\t break\n\n\t // This code is unreachable.\n\t // default:\n\t // throw invalidToken()\n\t }\n\n\t if (root === undefined) {\n\t root = value;\n\t } else {\n\t var parent = stack[stack.length - 1];\n\t if (Array.isArray(parent)) {\n\t parent.push(value);\n\t } else {\n\t Object.defineProperty(parent, key, {\n\t value: value,\n\t writable: true,\n\t enumerable: true,\n\t configurable: true,\n\t });\n\t }\n\t }\n\n\t if (value !== null && typeof value === 'object') {\n\t stack.push(value);\n\n\t if (Array.isArray(value)) {\n\t parseState = 'beforeArrayValue';\n\t } else {\n\t parseState = 'beforePropertyName';\n\t }\n\t } else {\n\t var current = stack[stack.length - 1];\n\t if (current == null) {\n\t parseState = 'end';\n\t } else if (Array.isArray(current)) {\n\t parseState = 'afterArrayValue';\n\t } else {\n\t parseState = 'afterPropertyValue';\n\t }\n\t }\n\t}\n\n\tfunction pop () {\n\t stack.pop();\n\n\t var current = stack[stack.length - 1];\n\t if (current == null) {\n\t parseState = 'end';\n\t } else if (Array.isArray(current)) {\n\t parseState = 'afterArrayValue';\n\t } else {\n\t parseState = 'afterPropertyValue';\n\t }\n\t}\n\n\t// This code is unreachable.\n\t// function invalidParseState () {\n\t// return new Error(`JSON5: invalid parse state '${parseState}'`)\n\t// }\n\n\t// This code is unreachable.\n\t// function invalidLexState (state) {\n\t// return new Error(`JSON5: invalid lex state '${state}'`)\n\t// }\n\n\tfunction invalidChar (c) {\n\t if (c === undefined) {\n\t return syntaxError((\"JSON5: invalid end of input at \" + line + \":\" + column))\n\t }\n\n\t return syntaxError((\"JSON5: invalid character '\" + (formatChar(c)) + \"' at \" + line + \":\" + column))\n\t}\n\n\tfunction invalidEOF () {\n\t return syntaxError((\"JSON5: invalid end of input at \" + line + \":\" + column))\n\t}\n\n\t// This code is unreachable.\n\t// function invalidToken () {\n\t// if (token.type === 'eof') {\n\t// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n\t// }\n\n\t// const c = String.fromCodePoint(token.value.codePointAt(0))\n\t// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n\t// }\n\n\tfunction invalidIdentifier () {\n\t column -= 5;\n\t return syntaxError((\"JSON5: invalid identifier character at \" + line + \":\" + column))\n\t}\n\n\tfunction separatorChar (c) {\n\t console.warn((\"JSON5: '\" + (formatChar(c)) + \"' in strings is not valid ECMAScript; consider escaping\"));\n\t}\n\n\tfunction formatChar (c) {\n\t var replacements = {\n\t \"'\": \"\\\\'\",\n\t '\"': '\\\\\"',\n\t '\\\\': '\\\\\\\\',\n\t '\\b': '\\\\b',\n\t '\\f': '\\\\f',\n\t '\\n': '\\\\n',\n\t '\\r': '\\\\r',\n\t '\\t': '\\\\t',\n\t '\\v': '\\\\v',\n\t '\\0': '\\\\0',\n\t '\\u2028': '\\\\u2028',\n\t '\\u2029': '\\\\u2029',\n\t };\n\n\t if (replacements[c]) {\n\t return replacements[c]\n\t }\n\n\t if (c < ' ') {\n\t var hexString = c.charCodeAt(0).toString(16);\n\t return '\\\\x' + ('00' + hexString).substring(hexString.length)\n\t }\n\n\t return c\n\t}\n\n\tfunction syntaxError (message) {\n\t var err = new SyntaxError(message);\n\t err.lineNumber = line;\n\t err.columnNumber = column;\n\t return err\n\t}\n\n\tvar stringify = function stringify (value, replacer, space) {\n\t var stack = [];\n\t var indent = '';\n\t var propertyList;\n\t var replacerFunc;\n\t var gap = '';\n\t var quote;\n\n\t if (\n\t replacer != null &&\n\t typeof replacer === 'object' &&\n\t !Array.isArray(replacer)\n\t ) {\n\t space = replacer.space;\n\t quote = replacer.quote;\n\t replacer = replacer.replacer;\n\t }\n\n\t if (typeof replacer === 'function') {\n\t replacerFunc = replacer;\n\t } else if (Array.isArray(replacer)) {\n\t propertyList = [];\n\t for (var i = 0, list = replacer; i < list.length; i += 1) {\n\t var v = list[i];\n\n\t var item = (void 0);\n\n\t if (typeof v === 'string') {\n\t item = v;\n\t } else if (\n\t typeof v === 'number' ||\n\t v instanceof String ||\n\t v instanceof Number\n\t ) {\n\t item = String(v);\n\t }\n\n\t if (item !== undefined && propertyList.indexOf(item) < 0) {\n\t propertyList.push(item);\n\t }\n\t }\n\t }\n\n\t if (space instanceof Number) {\n\t space = Number(space);\n\t } else if (space instanceof String) {\n\t space = String(space);\n\t }\n\n\t if (typeof space === 'number') {\n\t if (space > 0) {\n\t space = Math.min(10, Math.floor(space));\n\t gap = ' '.substr(0, space);\n\t }\n\t } else if (typeof space === 'string') {\n\t gap = space.substr(0, 10);\n\t }\n\n\t return serializeProperty('', {'': value})\n\n\t function serializeProperty (key, holder) {\n\t var value = holder[key];\n\t if (value != null) {\n\t if (typeof value.toJSON5 === 'function') {\n\t value = value.toJSON5(key);\n\t } else if (typeof value.toJSON === 'function') {\n\t value = value.toJSON(key);\n\t }\n\t }\n\n\t if (replacerFunc) {\n\t value = replacerFunc.call(holder, key, value);\n\t }\n\n\t if (value instanceof Number) {\n\t value = Number(value);\n\t } else if (value instanceof String) {\n\t value = String(value);\n\t } else if (value instanceof Boolean) {\n\t value = value.valueOf();\n\t }\n\n\t switch (value) {\n\t case null: return 'null'\n\t case true: return 'true'\n\t case false: return 'false'\n\t }\n\n\t if (typeof value === 'string') {\n\t return quoteString(value, false)\n\t }\n\n\t if (typeof value === 'number') {\n\t return String(value)\n\t }\n\n\t if (typeof value === 'object') {\n\t return Array.isArray(value) ? serializeArray(value) : serializeObject(value)\n\t }\n\n\t return undefined\n\t }\n\n\t function quoteString (value) {\n\t var quotes = {\n\t \"'\": 0.1,\n\t '\"': 0.2,\n\t };\n\n\t var replacements = {\n\t \"'\": \"\\\\'\",\n\t '\"': '\\\\\"',\n\t '\\\\': '\\\\\\\\',\n\t '\\b': '\\\\b',\n\t '\\f': '\\\\f',\n\t '\\n': '\\\\n',\n\t '\\r': '\\\\r',\n\t '\\t': '\\\\t',\n\t '\\v': '\\\\v',\n\t '\\0': '\\\\0',\n\t '\\u2028': '\\\\u2028',\n\t '\\u2029': '\\\\u2029',\n\t };\n\n\t var product = '';\n\n\t for (var i = 0; i < value.length; i++) {\n\t var c = value[i];\n\t switch (c) {\n\t case \"'\":\n\t case '\"':\n\t quotes[c]++;\n\t product += c;\n\t continue\n\n\t case '\\0':\n\t if (util.isDigit(value[i + 1])) {\n\t product += '\\\\x00';\n\t continue\n\t }\n\t }\n\n\t if (replacements[c]) {\n\t product += replacements[c];\n\t continue\n\t }\n\n\t if (c < ' ') {\n\t var hexString = c.charCodeAt(0).toString(16);\n\t product += '\\\\x' + ('00' + hexString).substring(hexString.length);\n\t continue\n\t }\n\n\t product += c;\n\t }\n\n\t var quoteChar = quote || Object.keys(quotes).reduce(function (a, b) { return (quotes[a] < quotes[b]) ? a : b; });\n\n\t product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);\n\n\t return quoteChar + product + quoteChar\n\t }\n\n\t function serializeObject (value) {\n\t if (stack.indexOf(value) >= 0) {\n\t throw TypeError('Converting circular structure to JSON5')\n\t }\n\n\t stack.push(value);\n\n\t var stepback = indent;\n\t indent = indent + gap;\n\n\t var keys = propertyList || Object.keys(value);\n\t var partial = [];\n\t for (var i = 0, list = keys; i < list.length; i += 1) {\n\t var key = list[i];\n\n\t var propertyString = serializeProperty(key, value);\n\t if (propertyString !== undefined) {\n\t var member = serializeKey(key) + ':';\n\t if (gap !== '') {\n\t member += ' ';\n\t }\n\t member += propertyString;\n\t partial.push(member);\n\t }\n\t }\n\n\t var final;\n\t if (partial.length === 0) {\n\t final = '{}';\n\t } else {\n\t var properties;\n\t if (gap === '') {\n\t properties = partial.join(',');\n\t final = '{' + properties + '}';\n\t } else {\n\t var separator = ',\\n' + indent;\n\t properties = partial.join(separator);\n\t final = '{\\n' + indent + properties + ',\\n' + stepback + '}';\n\t }\n\t }\n\n\t stack.pop();\n\t indent = stepback;\n\t return final\n\t }\n\n\t function serializeKey (key) {\n\t if (key.length === 0) {\n\t return quoteString(key, true)\n\t }\n\n\t var firstChar = String.fromCodePoint(key.codePointAt(0));\n\t if (!util.isIdStartChar(firstChar)) {\n\t return quoteString(key, true)\n\t }\n\n\t for (var i = firstChar.length; i < key.length; i++) {\n\t if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {\n\t return quoteString(key, true)\n\t }\n\t }\n\n\t return key\n\t }\n\n\t function serializeArray (value) {\n\t if (stack.indexOf(value) >= 0) {\n\t throw TypeError('Converting circular structure to JSON5')\n\t }\n\n\t stack.push(value);\n\n\t var stepback = indent;\n\t indent = indent + gap;\n\n\t var partial = [];\n\t for (var i = 0; i < value.length; i++) {\n\t var propertyString = serializeProperty(String(i), value);\n\t partial.push((propertyString !== undefined) ? propertyString : 'null');\n\t }\n\n\t var final;\n\t if (partial.length === 0) {\n\t final = '[]';\n\t } else {\n\t if (gap === '') {\n\t var properties = partial.join(',');\n\t final = '[' + properties + ']';\n\t } else {\n\t var separator = ',\\n' + indent;\n\t var properties$1 = partial.join(separator);\n\t final = '[\\n' + indent + properties$1 + ',\\n' + stepback + ']';\n\t }\n\t }\n\n\t stack.pop();\n\t indent = stepback;\n\t return final\n\t }\n\t};\n\n\tvar JSON5 = {\n\t parse: parse,\n\t stringify: stringify,\n\t};\n\n\tvar lib = JSON5;\n\n\tvar es5 = lib;\n\n\treturn es5;\n\n})));\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.memoryStorageDriver = factory());\n}(this, function () { 'use strict';\n\n function getSerializerPromise(localForageInstance) {\n if (getSerializerPromise.result) {\n return getSerializerPromise.result;\n }\n if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {\n Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));\n }\n getSerializerPromise.result = localForageInstance.getSerializer();\n return getSerializerPromise.result;\n }\n\n function executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n }\n\n var storageRepository = {};\n\n // Config the localStorage backend, using options set in the config.\n function _initStorage(options) {\n var self = this;\n\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n var database = storageRepository[dbInfo.name] = storageRepository[dbInfo.name] || {};\n var table = database[dbInfo.storeName] = database[dbInfo.storeName] || {};\n dbInfo.db = table;\n\n self._dbInfo = dbInfo;\n\n return getSerializerPromise(self).then(function (serializer) {\n dbInfo.serializer = serializer;\n });\n }\n\n function clear(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n delete db[key];\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function getItem(key, callback) {\n var self = this;\n\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n var result = db[key];\n\n if (result) {\n result = self._dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function iterate(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n\n var iterationNumber = 1;\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n var value = db[key];\n\n if (value) {\n value = self._dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key, iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function key(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n var result = null;\n var index = 0;\n\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n if (n === index) {\n result = key;\n break;\n }\n index++;\n }\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function keys(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n var keys = [];\n\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n keys.push(key);\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function length(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function removeItem(key, callback) {\n var self = this;\n\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n if (db.hasOwnProperty(key)) {\n delete db[key];\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function setItem(key, value, callback) {\n var self = this;\n\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n function serializeAsync(value) {\n return new Promise(function (resolve, reject) {\n self._dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n resolve(value);\n }\n });\n });\n }\n\n return serializeAsync(value).then(function (value) {\n var db = self._dbInfo.db;\n db[key] = value;\n return originalValue;\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n var memoryStorageDriver = {\n _driver: 'memoryStorageDriver',\n _initStorage: _initStorage,\n // _supports: function() { return true; }\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys\n };\n\n return memoryStorageDriver;\n\n}));","/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n var db = openreq.result;\n db.onversionchange = function (e) {\n // Triggered when the database is modified (e.g. adding an objectStore) or\n // deleted (even when initiated by other sessions in different tabs).\n // Closing the connection here prevents those operations from being blocked.\n // If the database is accessed again later by this instance, the connection\n // will be reopened or the database recreated as needed.\n e.target.close();\n };\n resolve(db);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(req.error);\n };\n\n req.onblocked = function () {\n // Closing all open connections in onversionchange handler should prevent this situation, but if\n // we do get here, it just means the request remains pending - eventually it will succeed or error\n console.warn('dropInstance blocked for database \"' + options.name + '\" until all open connections are closed');\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n","'use strict';\n\nfunction hasKey(obj, keys) {\n\tvar o = obj;\n\tkeys.slice(0, -1).forEach(function (key) {\n\t\to = o[key] || {};\n\t});\n\n\tvar key = keys[keys.length - 1];\n\treturn key in o;\n}\n\nfunction isNumber(x) {\n\tif (typeof x === 'number') { return true; }\n\tif ((/^0x[0-9a-f]+$/i).test(x)) { return true; }\n\treturn (/^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(e[-+]?\\d+)?$/).test(x);\n}\n\nfunction isConstructorOrProto(obj, key) {\n\treturn (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__';\n}\n\nmodule.exports = function (args, opts) {\n\tif (!opts) { opts = {}; }\n\n\tvar flags = {\n\t\tbools: {},\n\t\tstrings: {},\n\t\tunknownFn: null,\n\t};\n\n\tif (typeof opts.unknown === 'function') {\n\t\tflags.unknownFn = opts.unknown;\n\t}\n\n\tif (typeof opts.boolean === 'boolean' && opts.boolean) {\n\t\tflags.allBools = true;\n\t} else {\n\t\t[].concat(opts.boolean).filter(Boolean).forEach(function (key) {\n\t\t\tflags.bools[key] = true;\n\t\t});\n\t}\n\n\tvar aliases = {};\n\n\tfunction aliasIsBoolean(key) {\n\t\treturn aliases[key].some(function (x) {\n\t\t\treturn flags.bools[x];\n\t\t});\n\t}\n\n\tObject.keys(opts.alias || {}).forEach(function (key) {\n\t\taliases[key] = [].concat(opts.alias[key]);\n\t\taliases[key].forEach(function (x) {\n\t\t\taliases[x] = [key].concat(aliases[key].filter(function (y) {\n\t\t\t\treturn x !== y;\n\t\t\t}));\n\t\t});\n\t});\n\n\t[].concat(opts.string).filter(Boolean).forEach(function (key) {\n\t\tflags.strings[key] = true;\n\t\tif (aliases[key]) {\n\t\t\t[].concat(aliases[key]).forEach(function (k) {\n\t\t\t\tflags.strings[k] = true;\n\t\t\t});\n\t\t}\n\t});\n\n\tvar defaults = opts.default || {};\n\n\tvar argv = { _: [] };\n\n\tfunction argDefined(key, arg) {\n\t\treturn (flags.allBools && (/^--[^=]+$/).test(arg))\n\t\t\t|| flags.strings[key]\n\t\t\t|| flags.bools[key]\n\t\t\t|| aliases[key];\n\t}\n\n\tfunction setKey(obj, keys, value) {\n\t\tvar o = obj;\n\t\tfor (var i = 0; i < keys.length - 1; i++) {\n\t\t\tvar key = keys[i];\n\t\t\tif (isConstructorOrProto(o, key)) { return; }\n\t\t\tif (o[key] === undefined) { o[key] = {}; }\n\t\t\tif (\n\t\t\t\to[key] === Object.prototype\n\t\t\t\t|| o[key] === Number.prototype\n\t\t\t\t|| o[key] === String.prototype\n\t\t\t) {\n\t\t\t\to[key] = {};\n\t\t\t}\n\t\t\tif (o[key] === Array.prototype) { o[key] = []; }\n\t\t\to = o[key];\n\t\t}\n\n\t\tvar lastKey = keys[keys.length - 1];\n\t\tif (isConstructorOrProto(o, lastKey)) { return; }\n\t\tif (\n\t\t\to === Object.prototype\n\t\t\t|| o === Number.prototype\n\t\t\t|| o === String.prototype\n\t\t) {\n\t\t\to = {};\n\t\t}\n\t\tif (o === Array.prototype) { o = []; }\n\t\tif (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') {\n\t\t\to[lastKey] = value;\n\t\t} else if (Array.isArray(o[lastKey])) {\n\t\t\to[lastKey].push(value);\n\t\t} else {\n\t\t\to[lastKey] = [o[lastKey], value];\n\t\t}\n\t}\n\n\tfunction setArg(key, val, arg) {\n\t\tif (arg && flags.unknownFn && !argDefined(key, arg)) {\n\t\t\tif (flags.unknownFn(arg) === false) { return; }\n\t\t}\n\n\t\tvar value = !flags.strings[key] && isNumber(val)\n\t\t\t? Number(val)\n\t\t\t: val;\n\t\tsetKey(argv, key.split('.'), value);\n\n\t\t(aliases[key] || []).forEach(function (x) {\n\t\t\tsetKey(argv, x.split('.'), value);\n\t\t});\n\t}\n\n\tObject.keys(flags.bools).forEach(function (key) {\n\t\tsetArg(key, defaults[key] === undefined ? false : defaults[key]);\n\t});\n\n\tvar notFlags = [];\n\n\tif (args.indexOf('--') !== -1) {\n\t\tnotFlags = args.slice(args.indexOf('--') + 1);\n\t\targs = args.slice(0, args.indexOf('--'));\n\t}\n\n\tfor (var i = 0; i < args.length; i++) {\n\t\tvar arg = args[i];\n\t\tvar key;\n\t\tvar next;\n\n\t\tif ((/^--.+=/).test(arg)) {\n\t\t\t// Using [\\s\\S] instead of . because js doesn't support the\n\t\t\t// 'dotall' regex modifier. See:\n\t\t\t// http://stackoverflow.com/a/1068308/13216\n\t\t\tvar m = arg.match(/^--([^=]+)=([\\s\\S]*)$/);\n\t\t\tkey = m[1];\n\t\t\tvar value = m[2];\n\t\t\tif (flags.bools[key]) {\n\t\t\t\tvalue = value !== 'false';\n\t\t\t}\n\t\t\tsetArg(key, value, arg);\n\t\t} else if ((/^--no-.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--no-(.+)/)[1];\n\t\t\tsetArg(key, false, arg);\n\t\t} else if ((/^--.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--(.+)/)[1];\n\t\t\tnext = args[i + 1];\n\t\t\tif (\n\t\t\t\tnext !== undefined\n\t\t\t\t&& !(/^(-|--)[^-]/).test(next)\n\t\t\t\t&& !flags.bools[key]\n\t\t\t\t&& !flags.allBools\n\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t) {\n\t\t\t\tsetArg(key, next, arg);\n\t\t\t\ti += 1;\n\t\t\t} else if ((/^(true|false)$/).test(next)) {\n\t\t\t\tsetArg(key, next === 'true', arg);\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t}\n\t\t} else if ((/^-[^-]+/).test(arg)) {\n\t\t\tvar letters = arg.slice(1, -1).split('');\n\n\t\t\tvar broken = false;\n\t\t\tfor (var j = 0; j < letters.length; j++) {\n\t\t\t\tnext = arg.slice(j + 2);\n\n\t\t\t\tif (next === '-') {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') {\n\t\t\t\t\tsetArg(letters[j], next.slice(1), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(/[A-Za-z]/).test(letters[j])\n\t\t\t\t\t&& (/-?\\d+(\\.\\d*)?(e-?\\d+)?$/).test(next)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (letters[j + 1] && letters[j + 1].match(/\\W/)) {\n\t\t\t\t\tsetArg(letters[j], arg.slice(j + 2), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tkey = arg.slice(-1)[0];\n\t\t\tif (!broken && key !== '-') {\n\t\t\t\tif (\n\t\t\t\t\targs[i + 1]\n\t\t\t\t\t&& !(/^(-|--)[^-]/).test(args[i + 1])\n\t\t\t\t\t&& !flags.bools[key]\n\t\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(key, args[i + 1], arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) {\n\t\t\t\t\tsetArg(key, args[i + 1] === 'true', arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (!flags.unknownFn || flags.unknownFn(arg) !== false) {\n\t\t\t\targv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));\n\t\t\t}\n\t\t\tif (opts.stopEarly) {\n\t\t\t\targv._.push.apply(argv._, args.slice(i + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tObject.keys(defaults).forEach(function (k) {\n\t\tif (!hasKey(argv, k.split('.'))) {\n\t\t\tsetKey(argv, k.split('.'), defaults[k]);\n\n\t\t\t(aliases[k] || []).forEach(function (x) {\n\t\t\t\tsetKey(argv, x.split('.'), defaults[k]);\n\t\t\t});\n\t\t}\n\t});\n\n\tif (opts['--']) {\n\t\targv['--'] = notFlags.slice();\n\t} else {\n\t\tnotFlags.forEach(function (k) {\n\t\t\targv._.push(k);\n\t\t});\n\t}\n\n\treturn argv;\n};\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n\ttypeof define === 'function' && define.amd ? define(['exports'], factory) :\n\t(factory((global.Mock = global.Mock || {})));\n}(this, (function (exports) { 'use strict';\n\nvar commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nvar requiresPort = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) { return false; }\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n\nvar has = Object.prototype.hasOwnProperty;\nvar undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) { continue; }\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) { prefix = '?'; }\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) { continue; }\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nvar stringify = querystringify;\nvar parse = querystring;\n\nvar querystringify_1 = {\n\tstringify: stringify,\n\tparse: parse\n};\n\nvar CRHTLF = /[\\n\\r\\t]/g;\nvar slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//;\nvar protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i;\nvar windowsDriveLetter = /^[a-zA-Z]:/;\nvar whitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/;\n\n/**\n * Trim a given string.\n *\n * @param {String} str String to trim.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(whitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') { globalVar = window; }\n else if (typeof commonjsGlobal !== 'undefined') { globalVar = commonjsGlobal; }\n else if (typeof self !== 'undefined') { globalVar = self; }\n else { globalVar = {}; }\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) { delete finaldestination[key]; }\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) { continue; }\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4];\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') { return base; }\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) { unshift = true; }\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) { path.unshift(''); }\n if (last === '.' || last === '..') { path.push(''); }\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) { parser = querystringify_1.parse; }\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) { url[key] = url[key].toLowerCase(); }\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) { url.query = parser(url.query); }\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!requiresPort(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || querystringify_1.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!requiresPort(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) { value += ':'+ url.port; }\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (/:\\d+$/.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) { url[ins[1]] = url[ins[1]].toLowerCase(); }\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) { stringify = querystringify_1.stringify; }\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') { protocol += ':'; }\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) { result += ':'+ url.password; }\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':') { host += ':'; }\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) { result += '?' !== query.charAt(0) ? '?'+ query : query; }\n\n if (url.hash) { result += url.hash; }\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = querystringify_1;\n\nvar urlParse = Url;\n\n/*\n * This delay allows the thread to finish assigning its on* methods\n * before invoking the delay callback. This is purely a timing hack.\n * http://geekabyte.blogspot.com/2014/01/javascript-effect-of-setting-settimeout.html\n *\n * @param {callback: function} the callback which will be invoked after the timeout\n * @parma {context: object} the context in which to invoke the function\n */\nfunction delay(callback, context) {\n setTimeout(function (timeoutContext) { return callback.call(timeoutContext); }, 4, context);\n}\n\nfunction log(method, message) {\n /* eslint-disable no-console */\n if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'test') {\n console[method].call(null, message);\n }\n /* eslint-enable no-console */\n}\n\nfunction reject(array, callback) {\n if ( array === void 0 ) array = [];\n\n var results = [];\n array.forEach(function (itemInArray) {\n if (!callback(itemInArray)) {\n results.push(itemInArray);\n }\n });\n\n return results;\n}\n\nfunction filter(array, callback) {\n if ( array === void 0 ) array = [];\n\n var results = [];\n array.forEach(function (itemInArray) {\n if (callback(itemInArray)) {\n results.push(itemInArray);\n }\n });\n\n return results;\n}\n\n/*\n * EventTarget is an interface implemented by objects that can\n * receive events and may have listeners for them.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget\n */\nvar EventTarget = function EventTarget() {\n this.listeners = {};\n};\n\n/*\n * Ties a listener function to an event type which can later be invoked via the\n * dispatchEvent method.\n *\n * @param {string} type - the type of event (ie: 'open', 'message', etc.)\n * @param {function} listener - callback function to invoke when an event is dispatched matching the type\n * @param {boolean} useCapture - N/A TODO: implement useCapture functionality\n */\nEventTarget.prototype.addEventListener = function addEventListener (type, listener /* , useCapture */) {\n if (typeof listener === 'function') {\n if (!Array.isArray(this.listeners[type])) {\n this.listeners[type] = [];\n }\n\n // Only add the same function once\n if (filter(this.listeners[type], function (item) { return item === listener; }).length === 0) {\n this.listeners[type].push(listener);\n }\n }\n};\n\n/*\n * Removes the listener so it will no longer be invoked via the dispatchEvent method.\n *\n * @param {string} type - the type of event (ie: 'open', 'message', etc.)\n * @param {function} listener - callback function to invoke when an event is dispatched matching the type\n * @param {boolean} useCapture - N/A TODO: implement useCapture functionality\n */\nEventTarget.prototype.removeEventListener = function removeEventListener (type, removingListener /* , useCapture */) {\n var arrayOfListeners = this.listeners[type];\n this.listeners[type] = reject(arrayOfListeners, function (listener) { return listener === removingListener; });\n};\n\n/*\n * Invokes all listener functions that are listening to the given event.type property. Each\n * listener will be passed the event as the first argument.\n *\n * @param {object} event - event object which will be passed to all listeners of the event.type property\n */\nEventTarget.prototype.dispatchEvent = function dispatchEvent (event) {\n var this$1 = this;\n var customArguments = [], len = arguments.length - 1;\n while ( len-- > 0 ) customArguments[ len ] = arguments[ len + 1 ];\n\n var eventName = event.type;\n var listeners = this.listeners[eventName];\n\n if (!Array.isArray(listeners)) {\n return false;\n }\n\n listeners.forEach(function (listener) {\n if (customArguments.length > 0) {\n listener.apply(this$1, customArguments);\n } else {\n listener.call(this$1, event);\n }\n });\n\n return true;\n};\n\nfunction trimQueryPartFromURL(url) {\n var queryIndex = url.indexOf('?');\n return queryIndex >= 0 ? url.slice(0, queryIndex) : url;\n}\n\n/*\n * The network bridge is a way for the mock websocket object to 'communicate' with\n * all available servers. This is a singleton object so it is important that you\n * clean up urlMap whenever you are finished.\n */\nvar NetworkBridge = function NetworkBridge() {\n this.urlMap = {};\n};\n\n/*\n * Attaches a websocket object to the urlMap hash so that it can find the server\n * it is connected to and the server in turn can find it.\n *\n * @param {object} websocket - websocket object to add to the urlMap hash\n * @param {string} url\n */\nNetworkBridge.prototype.attachWebSocket = function attachWebSocket (websocket, url) {\n var serverURL = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverURL];\n\n if (connectionLookup && connectionLookup.server && connectionLookup.websockets.indexOf(websocket) === -1) {\n connectionLookup.websockets.push(websocket);\n return connectionLookup.server;\n }\n};\n\n/*\n * Attaches a websocket to a room\n */\nNetworkBridge.prototype.addMembershipToRoom = function addMembershipToRoom (websocket, room) {\n var connectionLookup = this.urlMap[trimQueryPartFromURL(websocket.url)];\n\n if (connectionLookup && connectionLookup.server && connectionLookup.websockets.indexOf(websocket) !== -1) {\n if (!connectionLookup.roomMemberships[room]) {\n connectionLookup.roomMemberships[room] = [];\n }\n\n connectionLookup.roomMemberships[room].push(websocket);\n }\n};\n\n/*\n * Attaches a server object to the urlMap hash so that it can find a websockets\n * which are connected to it and so that websockets can in turn can find it.\n *\n * @param {object} server - server object to add to the urlMap hash\n * @param {string} url\n */\nNetworkBridge.prototype.attachServer = function attachServer (server, url) {\n var serverUrl = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverUrl];\n\n if (!connectionLookup) {\n this.urlMap[serverUrl] = {\n server: server,\n websockets: [],\n roomMemberships: {}\n };\n\n return server;\n }\n};\n\n/*\n * Finds the server which is 'running' on the given url.\n *\n * @param {string} url - the url to use to find which server is running on it\n */\nNetworkBridge.prototype.serverLookup = function serverLookup (url) {\n var serverURL = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverURL];\n\n if (connectionLookup) {\n return connectionLookup.server;\n }\n};\n\n/*\n * Finds all websockets which is 'listening' on the given url.\n *\n * @param {string} url - the url to use to find all websockets which are associated with it\n * @param {string} room - if a room is provided, will only return sockets in this room\n * @param {class} broadcaster - socket that is broadcasting and is to be excluded from the lookup\n */\nNetworkBridge.prototype.websocketsLookup = function websocketsLookup (url, room, broadcaster) {\n var serverURL = trimQueryPartFromURL(url);\n var websockets;\n var connectionLookup = this.urlMap[serverURL];\n\n websockets = connectionLookup ? connectionLookup.websockets : [];\n\n if (room) {\n var members = connectionLookup.roomMemberships[room];\n websockets = members || [];\n }\n\n return broadcaster ? websockets.filter(function (websocket) { return websocket !== broadcaster; }) : websockets;\n};\n\n/*\n * Removes the entry associated with the url.\n *\n * @param {string} url\n */\nNetworkBridge.prototype.removeServer = function removeServer (url) {\n delete this.urlMap[trimQueryPartFromURL(url)];\n};\n\n/*\n * Removes the individual websocket from the map of associated websockets.\n *\n * @param {object} websocket - websocket object to remove from the url map\n * @param {string} url\n */\nNetworkBridge.prototype.removeWebSocket = function removeWebSocket (websocket, url) {\n var serverURL = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverURL];\n\n if (connectionLookup) {\n connectionLookup.websockets = reject(connectionLookup.websockets, function (socket) { return socket === websocket; });\n }\n};\n\n/*\n * Removes a websocket from a room\n */\nNetworkBridge.prototype.removeMembershipFromRoom = function removeMembershipFromRoom (websocket, room) {\n var connectionLookup = this.urlMap[trimQueryPartFromURL(websocket.url)];\n var memberships = connectionLookup.roomMemberships[room];\n\n if (connectionLookup && memberships !== null) {\n connectionLookup.roomMemberships[room] = reject(memberships, function (socket) { return socket === websocket; });\n }\n};\n\nvar networkBridge = new NetworkBridge(); // Note: this is a singleton\n\n/*\n * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n */\nvar CLOSE_CODES = {\n CLOSE_NORMAL: 1000,\n CLOSE_GOING_AWAY: 1001,\n CLOSE_PROTOCOL_ERROR: 1002,\n CLOSE_UNSUPPORTED: 1003,\n CLOSE_NO_STATUS: 1005,\n CLOSE_ABNORMAL: 1006,\n UNSUPPORTED_DATA: 1007,\n POLICY_VIOLATION: 1008,\n CLOSE_TOO_LARGE: 1009,\n MISSING_EXTENSION: 1010,\n INTERNAL_ERROR: 1011,\n SERVICE_RESTART: 1012,\n TRY_AGAIN_LATER: 1013,\n TLS_HANDSHAKE: 1015\n};\n\nvar ERROR_PREFIX = {\n CONSTRUCTOR_ERROR: \"Failed to construct 'WebSocket':\",\n CLOSE_ERROR: \"Failed to execute 'close' on 'WebSocket':\",\n EVENT: {\n CONSTRUCT: \"Failed to construct 'Event':\",\n MESSAGE: \"Failed to construct 'MessageEvent':\",\n CLOSE: \"Failed to construct 'CloseEvent':\"\n }\n};\n\nvar EventPrototype = function EventPrototype () {};\n\nEventPrototype.prototype.stopPropagation = function stopPropagation () {};\nEventPrototype.prototype.stopImmediatePropagation = function stopImmediatePropagation () {};\n\n// if no arguments are passed then the type is set to \"undefined\" on\n// chrome and safari.\nEventPrototype.prototype.initEvent = function initEvent (type, bubbles, cancelable) {\n if ( type === void 0 ) type = 'undefined';\n if ( bubbles === void 0 ) bubbles = false;\n if ( cancelable === void 0 ) cancelable = false;\n\n this.type = \"\" + type;\n this.bubbles = Boolean(bubbles);\n this.cancelable = Boolean(cancelable);\n};\n\nvar Event = (function (EventPrototype$$1) {\n function Event(type, eventInitConfig) {\n if ( eventInitConfig === void 0 ) eventInitConfig = {};\n\n EventPrototype$$1.call(this);\n\n if (!type) {\n throw new TypeError(((ERROR_PREFIX.EVENT_ERROR) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (typeof eventInitConfig !== 'object') {\n throw new TypeError(((ERROR_PREFIX.EVENT_ERROR) + \" parameter 2 ('eventInitDict') is not an object.\"));\n }\n\n var bubbles = eventInitConfig.bubbles;\n var cancelable = eventInitConfig.cancelable;\n\n this.type = \"\" + type;\n this.timeStamp = Date.now();\n this.target = null;\n this.srcElement = null;\n this.returnValue = true;\n this.isTrusted = false;\n this.eventPhase = 0;\n this.defaultPrevented = false;\n this.currentTarget = null;\n this.cancelable = cancelable ? Boolean(cancelable) : false;\n this.cancelBubble = false;\n this.bubbles = bubbles ? Boolean(bubbles) : false;\n }\n\n if ( EventPrototype$$1 ) Event.__proto__ = EventPrototype$$1;\n Event.prototype = Object.create( EventPrototype$$1 && EventPrototype$$1.prototype );\n Event.prototype.constructor = Event;\n\n return Event;\n}(EventPrototype));\n\nvar MessageEvent = (function (EventPrototype$$1) {\n function MessageEvent(type, eventInitConfig) {\n if ( eventInitConfig === void 0 ) eventInitConfig = {};\n\n EventPrototype$$1.call(this);\n\n if (!type) {\n throw new TypeError(((ERROR_PREFIX.EVENT.MESSAGE) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (typeof eventInitConfig !== 'object') {\n throw new TypeError(((ERROR_PREFIX.EVENT.MESSAGE) + \" parameter 2 ('eventInitDict') is not an object\"));\n }\n\n var bubbles = eventInitConfig.bubbles;\n var cancelable = eventInitConfig.cancelable;\n var data = eventInitConfig.data;\n var origin = eventInitConfig.origin;\n var lastEventId = eventInitConfig.lastEventId;\n var ports = eventInitConfig.ports;\n\n this.type = \"\" + type;\n this.timeStamp = Date.now();\n this.target = null;\n this.srcElement = null;\n this.returnValue = true;\n this.isTrusted = false;\n this.eventPhase = 0;\n this.defaultPrevented = false;\n this.currentTarget = null;\n this.cancelable = cancelable ? Boolean(cancelable) : false;\n this.canncelBubble = false;\n this.bubbles = bubbles ? Boolean(bubbles) : false;\n this.origin = \"\" + origin;\n this.ports = typeof ports === 'undefined' ? null : ports;\n this.data = typeof data === 'undefined' ? null : data;\n this.lastEventId = \"\" + (lastEventId || '');\n }\n\n if ( EventPrototype$$1 ) MessageEvent.__proto__ = EventPrototype$$1;\n MessageEvent.prototype = Object.create( EventPrototype$$1 && EventPrototype$$1.prototype );\n MessageEvent.prototype.constructor = MessageEvent;\n\n return MessageEvent;\n}(EventPrototype));\n\nvar CloseEvent = (function (EventPrototype$$1) {\n function CloseEvent(type, eventInitConfig) {\n if ( eventInitConfig === void 0 ) eventInitConfig = {};\n\n EventPrototype$$1.call(this);\n\n if (!type) {\n throw new TypeError(((ERROR_PREFIX.EVENT.CLOSE) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (typeof eventInitConfig !== 'object') {\n throw new TypeError(((ERROR_PREFIX.EVENT.CLOSE) + \" parameter 2 ('eventInitDict') is not an object\"));\n }\n\n var bubbles = eventInitConfig.bubbles;\n var cancelable = eventInitConfig.cancelable;\n var code = eventInitConfig.code;\n var reason = eventInitConfig.reason;\n var wasClean = eventInitConfig.wasClean;\n\n this.type = \"\" + type;\n this.timeStamp = Date.now();\n this.target = null;\n this.srcElement = null;\n this.returnValue = true;\n this.isTrusted = false;\n this.eventPhase = 0;\n this.defaultPrevented = false;\n this.currentTarget = null;\n this.cancelable = cancelable ? Boolean(cancelable) : false;\n this.cancelBubble = false;\n this.bubbles = bubbles ? Boolean(bubbles) : false;\n this.code = typeof code === 'number' ? parseInt(code, 10) : 0;\n this.reason = \"\" + (reason || '');\n this.wasClean = wasClean ? Boolean(wasClean) : false;\n }\n\n if ( EventPrototype$$1 ) CloseEvent.__proto__ = EventPrototype$$1;\n CloseEvent.prototype = Object.create( EventPrototype$$1 && EventPrototype$$1.prototype );\n CloseEvent.prototype.constructor = CloseEvent;\n\n return CloseEvent;\n}(EventPrototype));\n\n/*\n * Creates an Event object and extends it to allow full modification of\n * its properties.\n *\n * @param {object} config - within config you will need to pass type and optionally target\n */\nfunction createEvent(config) {\n var type = config.type;\n var target = config.target;\n var eventObject = new Event(type);\n\n if (target) {\n eventObject.target = target;\n eventObject.srcElement = target;\n eventObject.currentTarget = target;\n }\n\n return eventObject;\n}\n\n/*\n * Creates a MessageEvent object and extends it to allow full modification of\n * its properties.\n *\n * @param {object} config - within config: type, origin, data and optionally target\n */\nfunction createMessageEvent(config) {\n var type = config.type;\n var origin = config.origin;\n var data = config.data;\n var target = config.target;\n var messageEvent = new MessageEvent(type, {\n data: data,\n origin: origin\n });\n\n if (target) {\n messageEvent.target = target;\n messageEvent.srcElement = target;\n messageEvent.currentTarget = target;\n }\n\n return messageEvent;\n}\n\n/*\n * Creates a CloseEvent object and extends it to allow full modification of\n * its properties.\n *\n * @param {object} config - within config: type and optionally target, code, and reason\n */\nfunction createCloseEvent(config) {\n var code = config.code;\n var reason = config.reason;\n var type = config.type;\n var target = config.target;\n var wasClean = config.wasClean;\n\n if (!wasClean) {\n wasClean = code === CLOSE_CODES.CLOSE_NORMAL || code === CLOSE_CODES.CLOSE_NO_STATUS;\n }\n\n var closeEvent = new CloseEvent(type, {\n code: code,\n reason: reason,\n wasClean: wasClean\n });\n\n if (target) {\n closeEvent.target = target;\n closeEvent.srcElement = target;\n closeEvent.currentTarget = target;\n }\n\n return closeEvent;\n}\n\nfunction closeWebSocketConnection(context, code, reason) {\n context.readyState = WebSocket$1.CLOSING;\n\n var server = networkBridge.serverLookup(context.url);\n var closeEvent = createCloseEvent({\n type: 'close',\n target: context.target,\n code: code,\n reason: reason\n });\n\n delay(function () {\n networkBridge.removeWebSocket(context, context.url);\n\n context.readyState = WebSocket$1.CLOSED;\n context.dispatchEvent(closeEvent);\n\n if (server) {\n server.dispatchEvent(closeEvent, server);\n }\n }, context);\n}\n\nfunction failWebSocketConnection(context, code, reason) {\n context.readyState = WebSocket$1.CLOSING;\n\n var server = networkBridge.serverLookup(context.url);\n var closeEvent = createCloseEvent({\n type: 'close',\n target: context.target,\n code: code,\n reason: reason,\n wasClean: false\n });\n\n var errorEvent = createEvent({\n type: 'error',\n target: context.target\n });\n\n delay(function () {\n networkBridge.removeWebSocket(context, context.url);\n\n context.readyState = WebSocket$1.CLOSED;\n context.dispatchEvent(errorEvent);\n context.dispatchEvent(closeEvent);\n\n if (server) {\n server.dispatchEvent(closeEvent, server);\n }\n }, context);\n}\n\nfunction normalizeSendData(data) {\n if (Object.prototype.toString.call(data) !== '[object Blob]' && !(data instanceof ArrayBuffer)) {\n data = String(data);\n }\n\n return data;\n}\n\nvar proxies = new WeakMap();\n\nfunction proxyFactory(target) {\n if (proxies.has(target)) {\n return proxies.get(target);\n }\n\n var proxy = new Proxy(target, {\n get: function get(obj, prop) {\n if (prop === 'close') {\n return function close(options) {\n if ( options === void 0 ) options = {};\n\n var code = options.code || CLOSE_CODES.CLOSE_NORMAL;\n var reason = options.reason || '';\n\n closeWebSocketConnection(proxy, code, reason);\n };\n }\n\n if (prop === 'send') {\n return function send(data) {\n data = normalizeSendData(data);\n\n target.dispatchEvent(\n createMessageEvent({\n type: 'message',\n data: data,\n origin: this.url,\n target: target\n })\n );\n };\n }\n\n var toSocketName = function (type) { return (type === 'message' ? (\"server::\" + type) : type); };\n if (prop === 'on') {\n return function onWrapper(type, cb) {\n target.addEventListener(toSocketName(type), cb);\n };\n }\n if (prop === 'off') {\n return function offWrapper(type, cb) {\n target.removeEventListener(toSocketName(type), cb);\n };\n }\n\n if (prop === 'target') {\n return target;\n }\n\n return obj[prop];\n }\n });\n proxies.set(target, proxy);\n\n return proxy;\n}\n\nfunction lengthInUtf8Bytes(str) {\n // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.\n var m = encodeURIComponent(str).match(/%[89ABab]/g);\n return str.length + (m ? m.length : 0);\n}\n\nfunction urlVerification(url) {\n var urlRecord = new urlParse(url);\n var pathname = urlRecord.pathname;\n var protocol = urlRecord.protocol;\n var hash = urlRecord.hash;\n\n if (!url) {\n throw new TypeError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (!pathname) {\n urlRecord.pathname = '/';\n }\n\n if (protocol === '') {\n throw new SyntaxError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The URL '\" + (urlRecord.toString()) + \"' is invalid.\"));\n }\n\n if (protocol !== 'ws:' && protocol !== 'wss:') {\n throw new SyntaxError(\n ((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The URL's scheme must be either 'ws' or 'wss'. '\" + protocol + \"' is not allowed.\")\n );\n }\n\n if (hash !== '') {\n /* eslint-disable max-len */\n throw new SyntaxError(\n ((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The URL contains a fragment identifier ('\" + hash + \"'). Fragment identifiers are not allowed in WebSocket URLs.\")\n );\n /* eslint-enable max-len */\n }\n\n return urlRecord.toString();\n}\n\nfunction protocolVerification(protocols) {\n if ( protocols === void 0 ) protocols = [];\n\n if (!Array.isArray(protocols) && typeof protocols !== 'string') {\n throw new SyntaxError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The subprotocol '\" + (protocols.toString()) + \"' is invalid.\"));\n }\n\n if (typeof protocols === 'string') {\n protocols = [protocols];\n }\n\n var uniq = protocols\n .map(function (p) { return ({ count: 1, protocol: p }); })\n .reduce(function (a, b) {\n a[b.protocol] = (a[b.protocol] || 0) + b.count;\n return a;\n }, {});\n\n var duplicates = Object.keys(uniq).filter(function (a) { return uniq[a] > 1; });\n\n if (duplicates.length > 0) {\n throw new SyntaxError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The subprotocol '\" + (duplicates[0]) + \"' is duplicated.\"));\n }\n\n return protocols;\n}\n\n/*\n * The main websocket class which is designed to mimick the native WebSocket class as close\n * as possible.\n *\n * https://html.spec.whatwg.org/multipage/web-sockets.html\n */\nvar WebSocket$1 = (function (EventTarget$$1) {\n function WebSocket(url, protocols) {\n EventTarget$$1.call(this);\n\n this._onopen = null;\n this._onmessage = null;\n this._onerror = null;\n this._onclose = null;\n\n this.url = urlVerification(url);\n protocols = protocolVerification(protocols);\n this.protocol = protocols[0] || '';\n\n this.binaryType = 'blob';\n this.readyState = WebSocket.CONNECTING;\n\n var client = proxyFactory(this);\n var server = networkBridge.attachWebSocket(client, this.url);\n\n /*\n * This delay is needed so that we dont trigger an event before the callbacks have been\n * setup. For example:\n *\n * var socket = new WebSocket('ws://localhost');\n *\n * If we dont have the delay then the event would be triggered right here and this is\n * before the onopen had a chance to register itself.\n *\n * socket.onopen = () => { // this would never be called };\n *\n * and with the delay the event gets triggered here after all of the callbacks have been\n * registered :-)\n */\n delay(function delayCallback() {\n if (server) {\n if (\n server.options.verifyClient &&\n typeof server.options.verifyClient === 'function' &&\n !server.options.verifyClient()\n ) {\n this.readyState = WebSocket.CLOSED;\n\n log(\n 'error',\n (\"WebSocket connection to '\" + (this.url) + \"' failed: HTTP Authentication failed; no valid credentials available\")\n );\n\n networkBridge.removeWebSocket(client, this.url);\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(createCloseEvent({ type: 'close', target: this, code: CLOSE_CODES.CLOSE_NORMAL }));\n } else {\n if (server.options.selectProtocol && typeof server.options.selectProtocol === 'function') {\n var selectedProtocol = server.options.selectProtocol(protocols);\n var isFilled = selectedProtocol !== '';\n var isRequested = protocols.indexOf(selectedProtocol) !== -1;\n if (isFilled && !isRequested) {\n this.readyState = WebSocket.CLOSED;\n\n log('error', (\"WebSocket connection to '\" + (this.url) + \"' failed: Invalid Sub-Protocol\"));\n\n networkBridge.removeWebSocket(client, this.url);\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(createCloseEvent({ type: 'close', target: this, code: CLOSE_CODES.CLOSE_NORMAL }));\n return;\n }\n this.protocol = selectedProtocol;\n }\n this.readyState = WebSocket.OPEN;\n this.dispatchEvent(createEvent({ type: 'open', target: this }));\n server.dispatchEvent(createEvent({ type: 'connection' }), client);\n }\n } else {\n this.readyState = WebSocket.CLOSED;\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(createCloseEvent({ type: 'close', target: this, code: CLOSE_CODES.CLOSE_NORMAL }));\n\n log('error', (\"WebSocket connection to '\" + (this.url) + \"' failed\"));\n }\n }, this);\n }\n\n if ( EventTarget$$1 ) WebSocket.__proto__ = EventTarget$$1;\n WebSocket.prototype = Object.create( EventTarget$$1 && EventTarget$$1.prototype );\n WebSocket.prototype.constructor = WebSocket;\n\n var prototypeAccessors = { onopen: {},onmessage: {},onclose: {},onerror: {} };\n\n prototypeAccessors.onopen.get = function () {\n return this._onopen;\n };\n\n prototypeAccessors.onmessage.get = function () {\n return this._onmessage;\n };\n\n prototypeAccessors.onclose.get = function () {\n return this._onclose;\n };\n\n prototypeAccessors.onerror.get = function () {\n return this._onerror;\n };\n\n prototypeAccessors.onopen.set = function (listener) {\n this.removeEventListener('open', this._onopen);\n this._onopen = listener;\n this.addEventListener('open', listener);\n };\n\n prototypeAccessors.onmessage.set = function (listener) {\n this.removeEventListener('message', this._onmessage);\n this._onmessage = listener;\n this.addEventListener('message', listener);\n };\n\n prototypeAccessors.onclose.set = function (listener) {\n this.removeEventListener('close', this._onclose);\n this._onclose = listener;\n this.addEventListener('close', listener);\n };\n\n prototypeAccessors.onerror.set = function (listener) {\n this.removeEventListener('error', this._onerror);\n this._onerror = listener;\n this.addEventListener('error', listener);\n };\n\n WebSocket.prototype.send = function send (data) {\n var this$1 = this;\n\n if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) {\n throw new Error('WebSocket is already in CLOSING or CLOSED state');\n }\n\n // TODO: handle bufferedAmount\n\n var messageEvent = createMessageEvent({\n type: 'server::message',\n origin: this.url,\n data: normalizeSendData(data)\n });\n\n var server = networkBridge.serverLookup(this.url);\n\n if (server) {\n delay(function () {\n this$1.dispatchEvent(messageEvent, data);\n }, server);\n }\n };\n\n WebSocket.prototype.close = function close (code, reason) {\n if (code !== undefined) {\n if (typeof code !== 'number' || (code !== 1000 && (code < 3000 || code > 4999))) {\n throw new TypeError(\n ((ERROR_PREFIX.CLOSE_ERROR) + \" The code must be either 1000, or between 3000 and 4999. \" + code + \" is neither.\")\n );\n }\n }\n\n if (reason !== undefined) {\n var length = lengthInUtf8Bytes(reason);\n\n if (length > 123) {\n throw new SyntaxError(((ERROR_PREFIX.CLOSE_ERROR) + \" The message must not be greater than 123 bytes.\"));\n }\n }\n\n if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) {\n return;\n }\n\n var client = proxyFactory(this);\n if (this.readyState === WebSocket.CONNECTING) {\n failWebSocketConnection(client, code || CLOSE_CODES.CLOSE_ABNORMAL, reason);\n } else {\n closeWebSocketConnection(client, code || CLOSE_CODES.CLOSE_NO_STATUS, reason);\n }\n };\n\n Object.defineProperties( WebSocket.prototype, prototypeAccessors );\n\n return WebSocket;\n}(EventTarget));\n\nWebSocket$1.CONNECTING = 0;\nWebSocket$1.prototype.CONNECTING = WebSocket$1.CONNECTING;\nWebSocket$1.OPEN = 1;\nWebSocket$1.prototype.OPEN = WebSocket$1.OPEN;\nWebSocket$1.CLOSING = 2;\nWebSocket$1.prototype.CLOSING = WebSocket$1.CLOSING;\nWebSocket$1.CLOSED = 3;\nWebSocket$1.prototype.CLOSED = WebSocket$1.CLOSED;\n\n/*\n * The socket-io class is designed to mimick the real API as closely as possible.\n *\n * http://socket.io/docs/\n */\nvar SocketIO$1 = (function (EventTarget$$1) {\n function SocketIO(url, protocol) {\n var this$1 = this;\n if ( url === void 0 ) url = 'socket.io';\n if ( protocol === void 0 ) protocol = '';\n\n EventTarget$$1.call(this);\n\n this.binaryType = 'blob';\n var urlRecord = new urlParse(url);\n\n if (!urlRecord.pathname) {\n urlRecord.pathname = '/';\n }\n\n this.url = urlRecord.toString();\n this.readyState = SocketIO.CONNECTING;\n this.protocol = '';\n this.target = this;\n\n if (typeof protocol === 'string' || (typeof protocol === 'object' && protocol !== null)) {\n this.protocol = protocol;\n } else if (Array.isArray(protocol) && protocol.length > 0) {\n this.protocol = protocol[0];\n }\n\n var server = networkBridge.attachWebSocket(this, this.url);\n\n /*\n * Delay triggering the connection events so they can be defined in time.\n */\n delay(function delayCallback() {\n if (server) {\n this.readyState = SocketIO.OPEN;\n server.dispatchEvent(createEvent({ type: 'connection' }), server, this);\n server.dispatchEvent(createEvent({ type: 'connect' }), server, this); // alias\n this.dispatchEvent(createEvent({ type: 'connect', target: this }));\n } else {\n this.readyState = SocketIO.CLOSED;\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(\n createCloseEvent({\n type: 'close',\n target: this,\n code: CLOSE_CODES.CLOSE_NORMAL\n })\n );\n\n log('error', (\"Socket.io connection to '\" + (this.url) + \"' failed\"));\n }\n }, this);\n\n /**\n Add an aliased event listener for close / disconnect\n */\n this.addEventListener('close', function (event) {\n this$1.dispatchEvent(\n createCloseEvent({\n type: 'disconnect',\n target: event.target,\n code: event.code\n })\n );\n });\n }\n\n if ( EventTarget$$1 ) SocketIO.__proto__ = EventTarget$$1;\n SocketIO.prototype = Object.create( EventTarget$$1 && EventTarget$$1.prototype );\n SocketIO.prototype.constructor = SocketIO;\n\n var prototypeAccessors = { broadcast: {} };\n\n /*\n * Closes the SocketIO connection or connection attempt, if any.\n * If the connection is already CLOSED, this method does nothing.\n */\n SocketIO.prototype.close = function close () {\n if (this.readyState !== SocketIO.OPEN) {\n return undefined;\n }\n\n var server = networkBridge.serverLookup(this.url);\n networkBridge.removeWebSocket(this, this.url);\n\n this.readyState = SocketIO.CLOSED;\n this.dispatchEvent(\n createCloseEvent({\n type: 'close',\n target: this,\n code: CLOSE_CODES.CLOSE_NORMAL\n })\n );\n\n if (server) {\n server.dispatchEvent(\n createCloseEvent({\n type: 'disconnect',\n target: this,\n code: CLOSE_CODES.CLOSE_NORMAL\n }),\n server\n );\n }\n\n return this;\n };\n\n /*\n * Alias for Socket#close\n *\n * https://github.com/socketio/socket.io-client/blob/master/lib/socket.js#L383\n */\n SocketIO.prototype.disconnect = function disconnect () {\n return this.close();\n };\n\n /*\n * Submits an event to the server with a payload\n */\n SocketIO.prototype.emit = function emit (event) {\n var data = [], len = arguments.length - 1;\n while ( len-- > 0 ) data[ len ] = arguments[ len + 1 ];\n\n if (this.readyState !== SocketIO.OPEN) {\n throw new Error('SocketIO is already in CLOSING or CLOSED state');\n }\n\n var messageEvent = createMessageEvent({\n type: event,\n origin: this.url,\n data: data\n });\n\n var server = networkBridge.serverLookup(this.url);\n\n if (server) {\n server.dispatchEvent.apply(server, [ messageEvent ].concat( data ));\n }\n\n return this;\n };\n\n /*\n * Submits a 'message' event to the server.\n *\n * Should behave exactly like WebSocket#send\n *\n * https://github.com/socketio/socket.io-client/blob/master/lib/socket.js#L113\n */\n SocketIO.prototype.send = function send (data) {\n this.emit('message', data);\n return this;\n };\n\n /*\n * For broadcasting events to other connected sockets.\n *\n * e.g. socket.broadcast.emit('hi!');\n * e.g. socket.broadcast.to('my-room').emit('hi!');\n */\n prototypeAccessors.broadcast.get = function () {\n if (this.readyState !== SocketIO.OPEN) {\n throw new Error('SocketIO is already in CLOSING or CLOSED state');\n }\n\n var self = this;\n var server = networkBridge.serverLookup(this.url);\n if (!server) {\n throw new Error((\"SocketIO can not find a server at the specified URL (\" + (this.url) + \")\"));\n }\n\n return {\n emit: function emit(event, data) {\n server.emit(event, data, { websockets: networkBridge.websocketsLookup(self.url, null, self) });\n return self;\n },\n to: function to(room) {\n return server.to(room, self);\n },\n in: function in$1(room) {\n return server.in(room, self);\n }\n };\n };\n\n /*\n * For registering events to be received from the server\n */\n SocketIO.prototype.on = function on (type, callback) {\n this.addEventListener(type, callback);\n return this;\n };\n\n /*\n * Remove event listener\n *\n * https://github.com/component/emitter#emitteroffevent-fn\n */\n SocketIO.prototype.off = function off (type, callback) {\n this.removeEventListener(type, callback);\n };\n\n /*\n * Check if listeners have already been added for an event\n *\n * https://github.com/component/emitter#emitterhaslistenersevent\n */\n SocketIO.prototype.hasListeners = function hasListeners (type) {\n var listeners = this.listeners[type];\n if (!Array.isArray(listeners)) {\n return false;\n }\n return !!listeners.length;\n };\n\n /*\n * Join a room on a server\n *\n * http://socket.io/docs/rooms-and-namespaces/#joining-and-leaving\n */\n SocketIO.prototype.join = function join (room) {\n networkBridge.addMembershipToRoom(this, room);\n };\n\n /*\n * Get the websocket to leave the room\n *\n * http://socket.io/docs/rooms-and-namespaces/#joining-and-leaving\n */\n SocketIO.prototype.leave = function leave (room) {\n networkBridge.removeMembershipFromRoom(this, room);\n };\n\n SocketIO.prototype.to = function to (room) {\n return this.broadcast.to(room);\n };\n\n SocketIO.prototype.in = function in$1 () {\n return this.to.apply(null, arguments);\n };\n\n /*\n * Invokes all listener functions that are listening to the given event.type property. Each\n * listener will be passed the event as the first argument.\n *\n * @param {object} event - event object which will be passed to all listeners of the event.type property\n */\n SocketIO.prototype.dispatchEvent = function dispatchEvent (event) {\n var this$1 = this;\n var customArguments = [], len = arguments.length - 1;\n while ( len-- > 0 ) customArguments[ len ] = arguments[ len + 1 ];\n\n var eventName = event.type;\n var listeners = this.listeners[eventName];\n\n if (!Array.isArray(listeners)) {\n return false;\n }\n\n listeners.forEach(function (listener) {\n if (customArguments.length > 0) {\n listener.apply(this$1, customArguments);\n } else {\n // Regular WebSockets expect a MessageEvent but Socketio.io just wants raw data\n // payload instanceof MessageEvent works, but you can't isntance of NodeEvent\n // for now we detect if the output has data defined on it\n listener.call(this$1, event.data ? event.data : event);\n }\n });\n };\n\n Object.defineProperties( SocketIO.prototype, prototypeAccessors );\n\n return SocketIO;\n}(EventTarget));\n\nSocketIO$1.CONNECTING = 0;\nSocketIO$1.OPEN = 1;\nSocketIO$1.CLOSING = 2;\nSocketIO$1.CLOSED = 3;\n\n/*\n * Static constructor methods for the IO Socket\n */\nvar IO = function ioConstructor(url, protocol) {\n return new SocketIO$1(url, protocol);\n};\n\n/*\n * Alias the raw IO() constructor\n */\nIO.connect = function ioConnect(url, protocol) {\n /* eslint-disable new-cap */\n return IO(url, protocol);\n /* eslint-enable new-cap */\n};\n\nvar dedupe = function (arr) { return arr.reduce(function (deduped, b) {\n if (deduped.indexOf(b) > -1) { return deduped; }\n return deduped.concat(b);\n }, []); };\n\nfunction retrieveGlobalObject() {\n if (typeof window !== 'undefined') {\n return window;\n }\n\n return typeof process === 'object' && typeof require === 'function' && typeof global === 'object' ? global : this;\n}\n\nvar defaultOptions = {\n mock: true,\n verifyClient: null,\n selectProtocol: null\n};\n\nvar Server$1 = (function (EventTarget$$1) {\n function Server(url, options) {\n if ( options === void 0 ) options = defaultOptions;\n\n EventTarget$$1.call(this);\n var urlRecord = new urlParse(url);\n\n if (!urlRecord.pathname) {\n urlRecord.pathname = '/';\n }\n\n this.url = urlRecord.toString();\n\n this.originalWebSocket = null;\n var server = networkBridge.attachServer(this, this.url);\n\n if (!server) {\n this.dispatchEvent(createEvent({ type: 'error' }));\n throw new Error('A mock server is already listening on this url');\n }\n\n this.options = Object.assign({}, defaultOptions, options);\n\n if (this.options.mock) {\n this.mockWebsocket();\n }\n }\n\n if ( EventTarget$$1 ) Server.__proto__ = EventTarget$$1;\n Server.prototype = Object.create( EventTarget$$1 && EventTarget$$1.prototype );\n Server.prototype.constructor = Server;\n\n /*\n * Attaches the mock websocket object to the global object\n */\n Server.prototype.mockWebsocket = function mockWebsocket () {\n var globalObj = retrieveGlobalObject();\n\n this.originalWebSocket = globalObj.WebSocket;\n globalObj.WebSocket = WebSocket$1;\n };\n\n /*\n * Removes the mock websocket object from the global object\n */\n Server.prototype.restoreWebsocket = function restoreWebsocket () {\n var globalObj = retrieveGlobalObject();\n\n if (this.originalWebSocket !== null) {\n globalObj.WebSocket = this.originalWebSocket;\n }\n\n this.originalWebSocket = null;\n };\n\n /**\n * Removes itself from the urlMap so another server could add itself to the url.\n * @param {function} callback - The callback is called when the server is stopped\n */\n Server.prototype.stop = function stop (callback) {\n if ( callback === void 0 ) callback = function () {};\n\n if (this.options.mock) {\n this.restoreWebsocket();\n }\n\n networkBridge.removeServer(this.url);\n\n if (typeof callback === 'function') {\n callback();\n }\n };\n\n /*\n * This is the main function for the mock server to subscribe to the on events.\n *\n * ie: mockServer.on('connection', function() { console.log('a mock client connected'); });\n *\n * @param {string} type - The event key to subscribe to. Valid keys are: connection, message, and close.\n * @param {function} callback - The callback which should be called when a certain event is fired.\n */\n Server.prototype.on = function on (type, callback) {\n this.addEventListener(type, callback);\n };\n\n /*\n * Remove event listener\n */\n Server.prototype.off = function off (type, callback) {\n this.removeEventListener(type, callback);\n };\n\n /*\n * Closes the connection and triggers the onclose method of all listening\n * websockets. After that it removes itself from the urlMap so another server\n * could add itself to the url.\n *\n * @param {object} options\n */\n Server.prototype.close = function close (options) {\n if ( options === void 0 ) options = {};\n\n var code = options.code;\n var reason = options.reason;\n var wasClean = options.wasClean;\n var listeners = networkBridge.websocketsLookup(this.url);\n\n // Remove server before notifications to prevent immediate reconnects from\n // socket onclose handlers\n networkBridge.removeServer(this.url);\n\n listeners.forEach(function (socket) {\n socket.readyState = WebSocket$1.CLOSED;\n socket.dispatchEvent(\n createCloseEvent({\n type: 'close',\n target: socket.target,\n code: code || CLOSE_CODES.CLOSE_NORMAL,\n reason: reason || '',\n wasClean: wasClean\n })\n );\n });\n\n this.dispatchEvent(createCloseEvent({ type: 'close' }), this);\n };\n\n /*\n * Sends a generic message event to all mock clients.\n */\n Server.prototype.emit = function emit (event, data, options) {\n var this$1 = this;\n if ( options === void 0 ) options = {};\n\n var websockets = options.websockets;\n\n if (!websockets) {\n websockets = networkBridge.websocketsLookup(this.url);\n }\n\n var normalizedData;\n if (typeof options !== 'object' || arguments.length > 3) {\n data = Array.prototype.slice.call(arguments, 1, arguments.length);\n normalizedData = data.map(function (item) { return normalizeSendData(item); });\n } else {\n normalizedData = normalizeSendData(data);\n }\n\n websockets.forEach(function (socket) {\n var messageData = socket instanceof SocketIO$1 ? data : normalizedData;\n if (Array.isArray(messageData)) {\n socket.dispatchEvent.apply(\n socket, [ createMessageEvent({\n type: event,\n data: messageData,\n origin: this$1.url,\n target: socket.target\n }) ].concat( messageData )\n );\n } else {\n socket.dispatchEvent(\n createMessageEvent({\n type: event,\n data: messageData,\n origin: this$1.url,\n target: socket.target\n })\n );\n }\n });\n };\n\n /*\n * Returns an array of websockets which are listening to this server\n * TOOD: this should return a set and not be a method\n */\n Server.prototype.clients = function clients () {\n return networkBridge.websocketsLookup(this.url);\n };\n\n /*\n * Prepares a method to submit an event to members of the room\n *\n * e.g. server.to('my-room').emit('hi!');\n */\n Server.prototype.to = function to (room, broadcaster, broadcastList) {\n var this$1 = this;\n if ( broadcastList === void 0 ) broadcastList = [];\n\n var self = this;\n var websockets = dedupe(broadcastList.concat(networkBridge.websocketsLookup(this.url, room, broadcaster)));\n\n return {\n to: function (chainedRoom, chainedBroadcaster) { return this$1.to.call(this$1, chainedRoom, chainedBroadcaster, websockets); },\n emit: function emit(event, data) {\n self.emit(event, data, { websockets: websockets });\n }\n };\n };\n\n /*\n * Alias for Server.to\n */\n Server.prototype.in = function in$1 () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return this.to.apply(null, args);\n };\n\n /*\n * Simulate an event from the server to the clients. Useful for\n * simulating errors.\n */\n Server.prototype.simulate = function simulate (event) {\n var listeners = networkBridge.websocketsLookup(this.url);\n\n if (event === 'error') {\n listeners.forEach(function (socket) {\n socket.readyState = WebSocket$1.CLOSED;\n socket.dispatchEvent(createEvent({ type: 'error', target: socket.target }));\n });\n }\n };\n\n return Server;\n}(EventTarget));\n\n/*\n * Alternative constructor to support namespaces in socket.io\n *\n * http://socket.io/docs/rooms-and-namespaces/#custom-namespaces\n */\nServer$1.of = function of(url) {\n return new Server$1(url);\n};\n\nvar Server = Server$1;\nvar WebSocket = WebSocket$1;\nvar SocketIO$$1 = IO;\n\nexports.Server = Server;\nexports.WebSocket = WebSocket;\nexports.SocketIO = SocketIO$$1;\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n})));\n","// 'path' module extracted from Node.js v8.11.1 (only the posix part)\n// transplited with Babel\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));\n }\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n var res = '';\n var lastSegmentLength = 0;\n var lastSlash = -1;\n var dots = 0;\n var code;\n for (var i = 0; i <= path.length; ++i) {\n if (i < path.length)\n code = path.charCodeAt(i);\n else if (code === 47 /*/*/)\n break;\n else\n code = 47 /*/*/;\n if (code === 47 /*/*/) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n if (res.length > 2) {\n var lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0)\n res += '/..';\n else\n res = '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction _format(sep, pathObject) {\n var dir = pathObject.dir || pathObject.root;\n var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n if (!dir) {\n return base;\n }\n if (dir === pathObject.root) {\n return dir + base;\n }\n return dir + sep + base;\n}\n\nvar posix = {\n // path.resolve([from ...], to)\n resolve: function resolve() {\n var resolvedPath = '';\n var resolvedAbsolute = false;\n var cwd;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path;\n if (i >= 0)\n path = arguments[i];\n else {\n if (cwd === undefined)\n cwd = process.cwd();\n path = cwd;\n }\n\n assertPath(path);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0)\n return '/' + resolvedPath;\n else\n return '/';\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n } else {\n return '.';\n }\n },\n\n normalize: function normalize(path) {\n assertPath(path);\n\n if (path.length === 0) return '.';\n\n var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute);\n\n if (path.length === 0 && !isAbsolute) path = '.';\n if (path.length > 0 && trailingSeparator) path += '/';\n\n if (isAbsolute) return '/' + path;\n return path;\n },\n\n isAbsolute: function isAbsolute(path) {\n assertPath(path);\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n },\n\n join: function join() {\n if (arguments.length === 0)\n return '.';\n var joined;\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n assertPath(arg);\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += '/' + arg;\n }\n }\n if (joined === undefined)\n return '.';\n return posix.normalize(joined);\n },\n\n relative: function relative(from, to) {\n assertPath(from);\n assertPath(to);\n\n if (from === to) return '';\n\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to) return '';\n\n // Trim any leading backslashes\n var fromStart = 1;\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/)\n break;\n }\n var fromEnd = from.length;\n var fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n var toStart = 1;\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/)\n break;\n }\n var toEnd = to.length;\n var toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n var length = fromLen < toLen ? fromLen : toLen;\n var lastCommonSep = -1;\n var i = 0;\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0;\n }\n }\n break;\n }\n var fromCode = from.charCodeAt(fromStart + i);\n var toCode = to.charCodeAt(toStart + i);\n if (fromCode !== toCode)\n break;\n else if (fromCode === 47 /*/*/)\n lastCommonSep = i;\n }\n\n var out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0)\n out += '..';\n else\n out += '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return out + to.slice(toStart + lastCommonSep);\n else {\n toStart += lastCommonSep;\n if (to.charCodeAt(toStart) === 47 /*/*/)\n ++toStart;\n return to.slice(toStart);\n }\n },\n\n _makeLong: function _makeLong(path) {\n return path;\n },\n\n dirname: function dirname(path) {\n assertPath(path);\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) return '//';\n return path.slice(0, end);\n },\n\n basename: function basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n assertPath(path);\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return '';\n var extIdx = ext.length - 1;\n var firstNonSlashEnd = -1;\n for (i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n return path.slice(start, end);\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n }\n },\n\n extname: function extname(path) {\n assertPath(path);\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n }\n return _format('/', pathObject);\n },\n\n parse: function parse(path) {\n assertPath(path);\n\n var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0) return ret;\n var code = path.charCodeAt(0);\n var isAbsolute = code === 47 /*/*/;\n var start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n var i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot);\n ret.base = path.slice(1, end);\n } else {\n ret.name = path.slice(startPart, startDot);\n ret.base = path.slice(startPart, end);\n }\n ret.ext = path.slice(startDot, end);\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n return ret;\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n","'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n","import { startJupyterLiteServer } from './jlite';\nimport type { ThebeLiteGlobal } from './types';\n\ndeclare global {\n interface Window {\n thebeLite?: ThebeLiteGlobal;\n }\n}\n\nfunction setupThebeLite() {\n window.thebeLite = Object.assign(window.thebeLite ?? {}, { startJupyterLiteServer });\n}\n\nif (typeof window !== 'undefined') {\n console.debug('window is defined, setting up thebe-lite');\n setupThebeLite();\n console.debug('window.thebeLite', window.thebeLite);\n}\n\nexport * from './types';\nexport { startJupyterLiteServer, setupThebeLite };\n","import type { ServiceManager } from '@jupyterlab/services';\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport { JupyterLiteServer } from '@jupyterlite/server';\nimport { LiteServerConfig } from './types';\n\nconst serverExtensions = [import('@jupyterlite/server-extension')];\n\nasync function createModule(scope: string, module: string) {\n try {\n const factory = await (window as any)._JUPYTERLAB[scope].get(module);\n return factory();\n } catch (e) {\n console.warn(`Failed to create module: package: ${scope}; module: ${module}`);\n throw e;\n }\n}\n\n/**\n * Iterate over active plugins in an extension.\n */\nfunction* activePlugins(extension: any) {\n // Handle commonjs or es2015 modules\n let exports;\n if (Object.prototype.hasOwnProperty.call(extension, '__esModule')) {\n exports = extension.default;\n } else {\n // CommonJS exports.\n exports = extension;\n }\n\n const plugins = Array.isArray(exports) ? exports : [exports];\n for (const plugin of plugins) {\n yield plugin;\n }\n}\n\nexport async function startJupyterLiteServer(config?: LiteServerConfig): Promise {\n /**\n * This is sufficent to initialise the global object?\n */\n PageConfig.getOption('');\n\n /**\n * Do not rely on a configuration being on the document body, accept configuration via arguments\n * and set options on the page config directly\n */\n if (config?.litePluginSettings) {\n PageConfig.setOption('litePluginSettings', JSON.stringify(config.litePluginSettings));\n }\n\n /**\n * Seems like there are 4 different extensions we may want to handle\n *\n * liteExtension - essential, as these are how kernels are added\n * federatedExtension - general jupyterlab extensions\n * federatedMimeExtension - render extensions? e.g. @jupyterlab/javascript-extension, @jupyterlab/json-extension\n * federatedStyles - ?\n *\n * TODO we're not suppporting all of these yet\n */\n\n const litePluginsToRegister: JupyterLiteServer.IPluginModule[] = [];\n\n // Add the base serverlite extensions\n const baseServerExtensions = await Promise.all(serverExtensions);\n baseServerExtensions.forEach((p) => {\n for (const plugin of activePlugins(p)) {\n litePluginsToRegister.push(plugin);\n }\n });\n\n // TODO get federated extensions in from config argument?\n const extensions: any[] = [];\n\n const liteExtensionPromises: any[] = [import('@jupyterlite/pyodide-kernel-extension')];\n\n extensions.forEach((data) => {\n if (data.liteExtension) {\n liteExtensionPromises.push(createModule(data.name, data.extension));\n return;\n }\n });\n\n // Add the serverlite federated extensions.\n const federatedLiteExtensions = await Promise.allSettled(liteExtensionPromises);\n federatedLiteExtensions.forEach((p) => {\n if (p.status === 'fulfilled') {\n for (const plugin of activePlugins(p.value)) {\n litePluginsToRegister.push(plugin);\n }\n } else {\n console.error(p.reason);\n }\n });\n\n // create the in-browser JupyterLite Server\n const jupyterLiteServer = new JupyterLiteServer({} as any);\n jupyterLiteServer.registerPluginModules(litePluginsToRegister);\n // start the server\n await jupyterLiteServer.start();\n\n const { serviceManager } = jupyterLiteServer;\n await serviceManager.ready;\n\n // TODO\n return serviceManager as unknown as ServiceManager;\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ActivityMonitor = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * A class that monitors activity on a signal.\n */\nclass ActivityMonitor {\n /**\n * Construct a new activity monitor.\n */\n constructor(options) {\n this._timer = -1;\n this._timeout = -1;\n this._isDisposed = false;\n this._activityStopped = new signaling_1.Signal(this);\n options.signal.connect(this._onSignalFired, this);\n this._timeout = options.timeout || 1000;\n }\n /**\n * A signal emitted when activity has ceased.\n */\n get activityStopped() {\n return this._activityStopped;\n }\n /**\n * The timeout associated with the monitor, in milliseconds.\n */\n get timeout() {\n return this._timeout;\n }\n set timeout(value) {\n this._timeout = value;\n }\n /**\n * Test whether the monitor has been disposed.\n *\n * #### Notes\n * This is a read-only property.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources used by the activity monitor.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * A signal handler for the monitored signal.\n */\n _onSignalFired(sender, args) {\n clearTimeout(this._timer);\n this._sender = sender;\n this._args = args;\n this._timer = setTimeout(() => {\n this._activityStopped.emit({\n sender: this._sender,\n args: this._args\n });\n }, this._timeout);\n }\n}\nexports.ActivityMonitor = ActivityMonitor;\n//# sourceMappingURL=activitymonitor.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module coreutils\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./activitymonitor\"), exports);\n__exportStar(require(\"./interfaces\"), exports);\n__exportStar(require(\"./markdowncodeblocks\"), exports);\n__exportStar(require(\"./pageconfig\"), exports);\n__exportStar(require(\"./path\"), exports);\n__exportStar(require(\"./signal\"), exports);\n__exportStar(require(\"./text\"), exports);\n__exportStar(require(\"./time\"), exports);\n__exportStar(require(\"./url\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=interfaces.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MarkdownCodeBlocks = void 0;\n/**\n * The namespace for code block functions which help\n * in extract code from markdown text\n */\nvar MarkdownCodeBlocks;\n(function (MarkdownCodeBlocks) {\n MarkdownCodeBlocks.CODE_BLOCK_MARKER = '```';\n const markdownExtensions = [\n '.markdown',\n '.mdown',\n '.mkdn',\n '.md',\n '.mkd',\n '.mdwn',\n '.mdtxt',\n '.mdtext',\n '.text',\n '.txt',\n '.Rmd'\n ];\n class MarkdownCodeBlock {\n constructor(startLine) {\n this.startLine = startLine;\n this.code = '';\n this.endLine = -1;\n }\n }\n MarkdownCodeBlocks.MarkdownCodeBlock = MarkdownCodeBlock;\n /**\n * Check whether the given file extension is a markdown extension\n * @param extension - A file extension\n *\n * @returns true/false depending on whether this is a supported markdown extension\n */\n function isMarkdown(extension) {\n return markdownExtensions.indexOf(extension) > -1;\n }\n MarkdownCodeBlocks.isMarkdown = isMarkdown;\n /**\n * Construct all code snippets from current text\n * (this could be potentially optimized if we can cache and detect differences)\n * @param text - A string to parse codeblocks from\n *\n * @returns An array of MarkdownCodeBlocks.\n */\n function findMarkdownCodeBlocks(text) {\n if (!text || text === '') {\n return [];\n }\n const lines = text.split('\\n');\n const codeBlocks = [];\n let currentBlock = null;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n const lineContainsMarker = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER) === 0;\n const constructingBlock = currentBlock != null;\n // Skip this line if it is not part of any code block and doesn't contain a marker.\n if (!lineContainsMarker && !constructingBlock) {\n continue;\n }\n // Check if we are already constructing a code block.\n if (!constructingBlock) {\n // Start constructing a new code block.\n currentBlock = new MarkdownCodeBlock(lineIndex);\n // Check whether this is a single line code block of the form ```a = 10```.\n const firstIndex = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const lastIndex = line.lastIndexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const isSingleLine = firstIndex !== lastIndex;\n if (isSingleLine) {\n currentBlock.code = line.substring(firstIndex + MarkdownCodeBlocks.CODE_BLOCK_MARKER.length, lastIndex);\n currentBlock.endLine = lineIndex;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n }\n else if (currentBlock) {\n if (lineContainsMarker) {\n // End of block, finish it up.\n currentBlock.endLine = lineIndex - 1;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n else {\n // Append the current line.\n currentBlock.code += line + '\\n';\n }\n }\n }\n return codeBlocks;\n }\n MarkdownCodeBlocks.findMarkdownCodeBlocks = findMarkdownCodeBlocks;\n})(MarkdownCodeBlocks = exports.MarkdownCodeBlocks || (exports.MarkdownCodeBlocks = {}));\n//# sourceMappingURL=markdowncodeblocks.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PageConfig = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst minimist_1 = __importDefault(require(\"minimist\"));\nconst url_1 = require(\"./url\");\n/**\n * The namespace for `PageConfig` functions.\n */\nvar PageConfig;\n(function (PageConfig) {\n /**\n * Get global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n *\n * @returns The config value or an empty string if not found.\n *\n * #### Notes\n * All values are treated as strings.\n * For browser based applications, it is assumed that the page HTML\n * includes a script tag with the id `jupyter-config-data` containing the\n * configuration as valid JSON. In order to support the classic Notebook,\n * we fall back on checking for `body` data of the given `name`.\n *\n * For node applications, it is assumed that the process was launched\n * with a `--jupyter-config-data` option pointing to a JSON settings\n * file.\n */\n function getOption(name) {\n if (configData) {\n return configData[name] || getBodyData(name);\n }\n configData = Object.create(null);\n let found = false;\n // Use script tag if available.\n if (typeof document !== 'undefined' && document) {\n const el = document.getElementById('jupyter-config-data');\n if (el) {\n configData = JSON.parse(el.textContent || '');\n found = true;\n }\n }\n // Otherwise use CLI if given.\n if (!found && typeof process !== 'undefined' && process.argv) {\n try {\n const cli = (0, minimist_1.default)(process.argv.slice(2));\n const path = require('path');\n let fullPath = '';\n if ('jupyter-config-data' in cli) {\n fullPath = path.resolve(cli['jupyter-config-data']);\n }\n else if ('JUPYTER_CONFIG_DATA' in process.env) {\n fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);\n }\n if (fullPath) {\n // Force Webpack to ignore this require.\n // eslint-disable-next-line\n configData = eval('require')(fullPath);\n }\n }\n catch (e) {\n console.error(e);\n }\n }\n if (!coreutils_1.JSONExt.isObject(configData)) {\n configData = Object.create(null);\n }\n else {\n for (const key in configData) {\n // PageConfig expects strings\n if (typeof configData[key] !== 'string') {\n configData[key] = JSON.stringify(configData[key]);\n }\n }\n }\n return configData[name] || getBodyData(name);\n }\n PageConfig.getOption = getOption;\n /**\n * Set global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n * @param value - The value to set the option to.\n *\n * @returns The last config value or an empty string if it doesn't exist.\n */\n function setOption(name, value) {\n const last = getOption(name);\n configData[name] = value;\n return last;\n }\n PageConfig.setOption = setOption;\n /**\n * Get the base url for a Jupyter application, or the base url of the page.\n */\n function getBaseUrl() {\n return url_1.URLExt.normalize(getOption('baseUrl') || '/');\n }\n PageConfig.getBaseUrl = getBaseUrl;\n /**\n * Get the tree url for a JupyterLab application.\n */\n function getTreeUrl() {\n return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }\n PageConfig.getTreeUrl = getTreeUrl;\n /**\n * Get the base url for sharing links (usually baseUrl)\n */\n function getShareUrl() {\n return url_1.URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }\n PageConfig.getShareUrl = getShareUrl;\n /**\n * Get the tree url for shareable links.\n * Usually the same as treeUrl,\n * but overrideable e.g. when sharing with JupyterHub.\n */\n function getTreeShareUrl() {\n return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(), getOption('treeUrl')));\n }\n PageConfig.getTreeShareUrl = getTreeShareUrl;\n /**\n * Create a new URL given an optional mode and tree path.\n *\n * This is used to create URLS when the mode or tree path change as the user\n * changes mode or the current document in the main area. If fields in\n * options are omitted, the value in PageConfig will be used.\n *\n * @param options - IGetUrlOptions for the new path.\n */\n function getUrl(options) {\n var _a, _b, _c, _d;\n let path = options.toShare ? getShareUrl() : getBaseUrl();\n const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : getOption('mode');\n const workspace = (_b = options.workspace) !== null && _b !== void 0 ? _b : getOption('workspace');\n const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';\n path = url_1.URLExt.join(path, labOrDoc);\n if (workspace !== PageConfig.defaultWorkspace) {\n path = url_1.URLExt.join(path, 'workspaces', encodeURIComponent((_c = getOption('workspace')) !== null && _c !== void 0 ? _c : PageConfig.defaultWorkspace));\n }\n const treePath = (_d = options.treePath) !== null && _d !== void 0 ? _d : getOption('treePath');\n if (treePath) {\n path = url_1.URLExt.join(path, 'tree', url_1.URLExt.encodeParts(treePath));\n }\n return path;\n }\n PageConfig.getUrl = getUrl;\n PageConfig.defaultWorkspace = 'default';\n /**\n * Get the base websocket url for a Jupyter application, or an empty string.\n */\n function getWsUrl(baseUrl) {\n let wsUrl = getOption('wsUrl');\n if (!wsUrl) {\n baseUrl = baseUrl ? url_1.URLExt.normalize(baseUrl) : getBaseUrl();\n if (baseUrl.indexOf('http') !== 0) {\n return '';\n }\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n return url_1.URLExt.normalize(wsUrl);\n }\n PageConfig.getWsUrl = getWsUrl;\n /**\n * Returns the URL converting this notebook to a certain\n * format with nbconvert.\n */\n function getNBConvertURL({ path, format, download }) {\n const notebookPath = url_1.URLExt.encodeParts(path);\n const url = url_1.URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);\n if (download) {\n return url + '?download=true';\n }\n return url;\n }\n PageConfig.getNBConvertURL = getNBConvertURL;\n /**\n * Get the authorization token for a Jupyter application.\n */\n function getToken() {\n return getOption('token') || getBodyData('jupyterApiToken');\n }\n PageConfig.getToken = getToken;\n /**\n * Get the Notebook version info [major, minor, patch].\n */\n function getNotebookVersion() {\n const notebookVersion = getOption('notebookVersion');\n if (notebookVersion === '') {\n return [0, 0, 0];\n }\n return JSON.parse(notebookVersion);\n }\n PageConfig.getNotebookVersion = getNotebookVersion;\n /**\n * Private page config data for the Jupyter application.\n */\n let configData = null;\n /**\n * Get a url-encoded item from `body.data` and decode it\n * We should never have any encoded URLs anywhere else in code\n * until we are building an actual request.\n */\n function getBodyData(key) {\n if (typeof document === 'undefined' || !document.body) {\n return '';\n }\n const val = document.body.dataset[key];\n if (typeof val === 'undefined') {\n return '';\n }\n return decodeURIComponent(val);\n }\n /**\n * The namespace for page config `Extension` functions.\n */\n let Extension;\n (function (Extension) {\n /**\n * Populate an array from page config.\n *\n * @param key - The page config key (e.g., `deferredExtensions`).\n *\n * #### Notes\n * This is intended for `deferredExtensions` and `disabledExtensions`.\n */\n function populate(key) {\n try {\n const raw = getOption(key);\n if (raw) {\n return JSON.parse(raw);\n }\n }\n catch (error) {\n console.warn(`Unable to parse ${key}.`, error);\n }\n return [];\n }\n /**\n * The collection of deferred extensions in page config.\n */\n Extension.deferred = populate('deferredExtensions');\n /**\n * The collection of disabled extensions in page config.\n */\n Extension.disabled = populate('disabledExtensions');\n /**\n * Returns whether a plugin is deferred.\n *\n * @param id - The plugin ID.\n */\n function isDeferred(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.deferred.some(val => val === id || (extName && val === extName));\n }\n Extension.isDeferred = isDeferred;\n /**\n * Returns whether a plugin is disabled.\n *\n * @param id - The plugin ID.\n */\n function isDisabled(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.disabled.some(val => val === id || (extName && val === extName));\n }\n Extension.isDisabled = isDisabled;\n })(Extension = PageConfig.Extension || (PageConfig.Extension = {}));\n})(PageConfig = exports.PageConfig || (exports.PageConfig = {}));\n//# sourceMappingURL=pageconfig.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PathExt = void 0;\nconst path_1 = require(\"path\");\n/**\n * The namespace for path-related functions.\n *\n * Note that Jupyter server paths do not start with a leading slash.\n */\nvar PathExt;\n(function (PathExt) {\n /**\n * Join all arguments together and normalize the resulting path.\n * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n *\n * @param paths - The string paths to join.\n */\n function join(...paths) {\n const path = path_1.posix.join(...paths);\n return path === '.' ? '' : removeSlash(path);\n }\n PathExt.join = join;\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * Often used to extract the file name from a fully qualified path.\n *\n * @param path - The path to evaluate.\n *\n * @param ext - An extension to remove from the result.\n */\n function basename(path, ext) {\n return path_1.posix.basename(path, ext);\n }\n PathExt.basename = basename;\n /**\n * Get the directory name of a path, similar to the Unix dirname command.\n * When an empty path is given, returns the root path.\n *\n * @param path - The file path.\n */\n function dirname(path) {\n const dir = removeSlash(path_1.posix.dirname(path));\n return dir === '.' ? '' : dir;\n }\n PathExt.dirname = dirname;\n /**\n * Get the extension of the path.\n *\n * @param path - The file path.\n *\n * @returns the extension of the file.\n *\n * #### Notes\n * The extension is the string from the last occurrence of the `.`\n * character to end of string in the last portion of the path, inclusive.\n * If there is no `.` in the last portion of the path, or if the first\n * character of the basename of path [[basename]] is `.`, then an\n * empty string is returned.\n */\n function extname(path) {\n return path_1.posix.extname(path);\n }\n PathExt.extname = extname;\n /**\n * Normalize a string path, reducing '..' and '.' parts.\n * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n * When an empty path is given, returns the root path.\n *\n * @param path - The string path to normalize.\n */\n function normalize(path) {\n if (path === '') {\n return '';\n }\n return removeSlash(path_1.posix.normalize(path));\n }\n PathExt.normalize = normalize;\n /**\n * Resolve a sequence of paths or path segments into an absolute path.\n * The root path in the application has no leading slash, so it is removed.\n *\n * @param parts - The paths to join.\n *\n * #### Notes\n * The right-most parameter is considered \\{to\\}. Other parameters are considered an array of \\{from\\}.\n *\n * Starting from leftmost \\{from\\} parameter, resolves \\{to\\} to an absolute path.\n *\n * If \\{to\\} isn't already absolute, \\{from\\} arguments are prepended in right to left order, until an absolute path is found. If after using all \\{from\\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n */\n function resolve(...parts) {\n return removeSlash(path_1.posix.resolve(...parts));\n }\n PathExt.resolve = resolve;\n /**\n * Solve the relative path from \\{from\\} to \\{to\\}.\n *\n * @param from - The source path.\n *\n * @param to - The target path.\n *\n * #### Notes\n * If from and to each resolve to the same path (after calling\n * path.resolve() on each), a zero-length string is returned.\n * If a zero-length string is passed as from or to, `/`\n * will be used instead of the zero-length strings.\n */\n function relative(from, to) {\n return removeSlash(path_1.posix.relative(from, to));\n }\n PathExt.relative = relative;\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * @param extension - the file extension.\n *\n * #### Notes\n * Adds a leading dot if not present and converts to lower case.\n */\n function normalizeExtension(extension) {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n PathExt.normalizeExtension = normalizeExtension;\n /**\n * Remove the leading slash from a path.\n *\n * @param path: the path from which to remove a leading slash.\n */\n function removeSlash(path) {\n if (path.indexOf('/') === 0) {\n path = path.slice(1);\n }\n return path;\n }\n PathExt.removeSlash = removeSlash;\n})(PathExt = exports.PathExt || (exports.PathExt = {}));\n//# sourceMappingURL=path.js.map","\"use strict\";\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.signalToPromise = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * Convert a signal into a promise for the first emitted value.\n *\n * @param signal - The signal we are listening to.\n * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)\n *\n * @returns a Promise that resolves with a `(sender, args)` pair.\n */\nfunction signalToPromise(signal, timeout) {\n const waitForSignal = new coreutils_1.PromiseDelegate();\n function cleanup() {\n signal.disconnect(slot);\n }\n function slot(sender, args) {\n cleanup();\n waitForSignal.resolve([sender, args]);\n }\n signal.connect(slot);\n if ((timeout !== null && timeout !== void 0 ? timeout : 0) > 0) {\n setTimeout(() => {\n cleanup();\n waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);\n }, timeout);\n }\n return waitForSignal.promise;\n}\nexports.signalToPromise = signalToPromise;\n//# sourceMappingURL=signal.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Text = void 0;\n/**\n * The namespace for text-related functions.\n */\nvar Text;\n(function (Text) {\n // javascript stores text as utf16 and string indices use \"code units\",\n // which stores high-codepoint characters as \"surrogate pairs\",\n // which occupy two indices in the javascript string.\n // We need to translate cursor_pos in the Jupyter protocol (in characters)\n // to js offset (with surrogate pairs taking two spots).\n const HAS_SURROGATES = '𝐚'.length > 1;\n /**\n * Convert a javascript string index into a unicode character offset\n *\n * @param jsIdx - The javascript string index (counting surrogate pairs)\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The unicode character offset\n */\n function jsIndexToCharIndex(jsIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return jsIdx;\n }\n let charIdx = jsIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n charIdx--;\n i++;\n }\n }\n }\n return charIdx;\n }\n Text.jsIndexToCharIndex = jsIndexToCharIndex;\n /**\n * Convert a unicode character offset to a javascript string index.\n *\n * @param charIdx - The index in unicode characters\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The js-native index\n */\n function charIndexToJsIndex(charIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return charIdx;\n }\n let jsIdx = charIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n jsIdx++;\n i++;\n }\n }\n }\n return jsIdx;\n }\n Text.charIndexToJsIndex = charIndexToJsIndex;\n /**\n * Given a 'snake-case', 'snake_case', 'snake:case', or\n * 'snake case' string, will return the camel case version: 'snakeCase'.\n *\n * @param str: the snake-case input string.\n *\n * @param upper: default = false. If true, the first letter of the\n * returned string will be capitalized.\n *\n * @returns the camel case version of the input string.\n */\n function camelCase(str, upper = false) {\n return str.replace(/^(\\w)|[\\s-_:]+(\\w)/g, function (match, p1, p2) {\n if (p2) {\n return p2.toUpperCase();\n }\n else {\n return upper ? p1.toUpperCase() : p1.toLowerCase();\n }\n });\n }\n Text.camelCase = camelCase;\n /**\n * Given a string, title case the words in the string.\n *\n * @param str: the string to title case.\n *\n * @returns the same string, but with each word capitalized.\n */\n function titleCase(str) {\n return (str || '')\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n Text.titleCase = titleCase;\n})(Text = exports.Text || (exports.Text = {}));\n//# sourceMappingURL=text.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Time = void 0;\n/**\n * A list of time units with their associated value in milliseconds.\n */\nconst UNITS = [\n { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },\n { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },\n { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },\n { name: 'hours', milliseconds: 60 * 60 * 1000 },\n { name: 'minutes', milliseconds: 60 * 1000 },\n { name: 'seconds', milliseconds: 1000 }\n];\n/**\n * The namespace for date functions.\n */\nvar Time;\n(function (Time) {\n /**\n * Convert a timestring to a human readable string (e.g. 'two minutes ago').\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function formatHuman(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' });\n const delta = new Date(value).getTime() - Date.now();\n for (let unit of UNITS) {\n const amount = Math.ceil(delta / unit.milliseconds);\n if (amount === 0) {\n continue;\n }\n return formatter.format(amount, unit.name);\n }\n return formatter.format(0, 'seconds');\n }\n Time.formatHuman = formatHuman;\n /**\n * Convenient helper to convert a timestring to a date format.\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function format(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.DateTimeFormat(lang, {\n dateStyle: 'short',\n timeStyle: 'short'\n });\n return formatter.format(new Date(value));\n }\n Time.format = format;\n})(Time = exports.Time || (exports.Time = {}));\n//# sourceMappingURL=time.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URLExt = void 0;\nconst path_1 = require(\"path\");\nconst url_parse_1 = __importDefault(require(\"url-parse\"));\n/**\n * The namespace for URL-related functions.\n */\nvar URLExt;\n(function (URLExt) {\n /**\n * Parse a url into a URL object.\n *\n * @param urlString - The URL string to parse.\n *\n * @returns A URL object.\n */\n function parse(url) {\n if (typeof document !== 'undefined' && document) {\n const a = document.createElement('a');\n a.href = url;\n return a;\n }\n return (0, url_parse_1.default)(url);\n }\n URLExt.parse = parse;\n /**\n * Parse URL and retrieve hostname\n *\n * @param url - The URL string to parse\n *\n * @returns a hostname string value\n */\n function getHostName(url) {\n return (0, url_parse_1.default)(url).hostname;\n }\n URLExt.getHostName = getHostName;\n function normalize(url) {\n return url && parse(url).toString();\n }\n URLExt.normalize = normalize;\n /**\n * Join a sequence of url components and normalizes as in node `path.join`.\n *\n * @param parts - The url components.\n *\n * @returns the joined url.\n */\n function join(...parts) {\n let u = (0, url_parse_1.default)(parts[0], {});\n // Schema-less URL can be only parsed as relative to a base URL\n // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326\n const isSchemaLess = u.protocol === '' && u.slashes;\n if (isSchemaLess) {\n u = (0, url_parse_1.default)(parts[0], 'https:' + parts[0]);\n }\n const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${u.auth}${u.auth ? '@' : ''}${u.host}`;\n // If there was a prefix, then the first path must start at the root.\n const path = path_1.posix.join(`${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`, ...parts.slice(1));\n return `${prefix}${path === '.' ? '' : path}`;\n }\n URLExt.join = join;\n /**\n * Encode the components of a multi-segment url.\n *\n * @param url - The url to encode.\n *\n * @returns the encoded url.\n *\n * #### Notes\n * Preserves the `'/'` separators.\n * Should not include the base url, since all parts are escaped.\n */\n function encodeParts(url) {\n return join(...url.split('/').map(encodeURIComponent));\n }\n URLExt.encodeParts = encodeParts;\n /**\n * Return a serialized object string suitable for a query.\n *\n * @param object - The source object.\n *\n * @returns an encoded url query.\n *\n * #### Notes\n * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).\n */\n function objectToQueryString(value) {\n const keys = Object.keys(value).filter(key => key.length > 0);\n if (!keys.length) {\n return '';\n }\n return ('?' +\n keys\n .map(key => {\n const content = encodeURIComponent(String(value[key]));\n return key + (content ? '=' + content : '');\n })\n .join('&'));\n }\n URLExt.objectToQueryString = objectToQueryString;\n /**\n * Return a parsed object that represents the values in a query string.\n */\n function queryStringToObject(value) {\n return value\n .replace(/^\\?/, '')\n .split('&')\n .reduce((acc, val) => {\n const [key, value] = val.split('=');\n if (key.length > 0) {\n acc[key] = decodeURIComponent(value || '');\n }\n return acc;\n }, {});\n }\n URLExt.queryStringToObject = queryStringToObject;\n /**\n * Test whether the url is a local url.\n *\n * #### Notes\n * This function returns `false` for any fully qualified url, including\n * `data:`, `file:`, and `//` protocol URLs.\n */\n function isLocal(url) {\n const { protocol } = parse(url);\n return ((!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&\n url.indexOf('/') !== 0);\n }\n URLExt.isLocal = isLocal;\n})(URLExt = exports.URLExt || (exports.URLExt = {}));\n//# sourceMappingURL=url.js.map","import { PageConfig } from '@jupyterlab/coreutils';\nimport mime from 'mime';\nimport { Token } from '@lumino/coreutils';\n/**\n * The token for the settings service.\n */\nexport const IContents = new Token('@jupyterlite/contents:IContents');\n/**\n * Commonly-used mimetypes\n */\nexport var MIME;\n(function (MIME) {\n MIME.JSON = 'application/json';\n MIME.PLAIN_TEXT = 'text/plain';\n MIME.OCTET_STREAM = 'octet/stream';\n})(MIME || (MIME = {}));\n/**\n * A namespace for file constructs.\n */\nexport var FILE;\n(function (FILE) {\n /**\n * Build-time configured file types.\n */\n const TYPES = JSON.parse(PageConfig.getOption('fileTypes') || '{}');\n /**\n * Get a mimetype (or fallback).\n */\n function getType(ext, defaultType = null) {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext && fileType.mimeTypes && fileType.mimeTypes.length) {\n return fileType.mimeTypes[0];\n }\n }\n }\n return mime.getType(ext) || defaultType || MIME.OCTET_STREAM;\n }\n FILE.getType = getType;\n /**\n * Determine whether the given extension matches a given fileFormat.\n */\n function hasFormat(ext, fileFormat) {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n if (fileType.fileFormat !== fileFormat) {\n continue;\n }\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext) {\n return true;\n }\n }\n }\n return false;\n }\n FILE.hasFormat = hasFormat;\n})(FILE || (FILE = {}));\n/**\n * The token for the BroadcastChannel broadcaster.\n */\nexport const IBroadcastChannelWrapper = new Token('@jupyterlite/contents:IBroadcastChannelWrapper');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Token } from '@lumino/coreutils';\n/**\n * The token for the kernels service.\n */\nexport const IKernels = new Token('@jupyterlite/kernel:IKernels');\n/**\n * The kernel name of last resort.\n */\nexport const FALLBACK_KERNEL = 'javascript';\n/**\n * The token for the kernel spec service.\n */\nexport const IKernelSpecs = new Token('@jupyterlite/kernel:IKernelSpecs');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { IServiceWorkerManager, } from '@jupyterlite/server';\nimport { IKernelSpecs } from '@jupyterlite/kernel';\nimport { IBroadcastChannelWrapper } from '@jupyterlite/contents';\nexport * as KERNEL_SETTINGS_SCHEMA from '../schema/kernel.v0.schema.json';\nimport KERNEL_ICON_SVG_STR from '../style/img/pyodide.svg';\nconst KERNEL_ICON_URL = `data:image/svg+xml;base64,${btoa(KERNEL_ICON_SVG_STR)}`;\n/**\n * The default CDN fallback for Pyodide\n */\nconst PYODIDE_CDN_URL = 'https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js';\n/**\n * The id for the extension, and key in the litePlugins.\n */\nconst PLUGIN_ID = '@jupyterlite/pyodide-kernel-extension:kernel';\n/**\n * A plugin to register the Pyodide kernel.\n */\nconst kernel = {\n id: PLUGIN_ID,\n autoStart: true,\n requires: [IKernelSpecs],\n optional: [IServiceWorkerManager, IBroadcastChannelWrapper],\n activate: (app, kernelspecs, serviceWorker, broadcastChannel) => {\n const config = JSON.parse(PageConfig.getOption('litePluginSettings') || '{}')[PLUGIN_ID] || {};\n const url = config.pyodideUrl || PYODIDE_CDN_URL;\n const pyodideUrl = URLExt.parse(url).href;\n const pipliteWheelUrl = config.pipliteWheelUrl\n ? URLExt.parse(config.pipliteWheelUrl).href\n : undefined;\n const rawPipUrls = config.pipliteUrls || [];\n const pipliteUrls = rawPipUrls.map((pipUrl) => URLExt.parse(pipUrl).href);\n const disablePyPIFallback = !!config.disablePyPIFallback;\n kernelspecs.register({\n spec: {\n name: 'python',\n display_name: 'Python (Pyodide)',\n language: 'python',\n argv: [],\n resources: {\n 'logo-32x32': KERNEL_ICON_URL,\n 'logo-64x64': KERNEL_ICON_URL,\n },\n },\n create: async (options) => {\n const { PyodideKernel } = await import('@jupyterlite/pyodide-kernel');\n const mountDrive = !!((serviceWorker === null || serviceWorker === void 0 ? void 0 : serviceWorker.enabled) && (broadcastChannel === null || broadcastChannel === void 0 ? void 0 : broadcastChannel.enabled));\n if (mountDrive) {\n console.info('Pyodide contents will be synced with Jupyter Contents');\n }\n else {\n console.warn('Pyodide contents will NOT be synced with Jupyter Contents');\n }\n return new PyodideKernel({\n ...options,\n pyodideUrl,\n pipliteWheelUrl,\n pipliteUrls,\n disablePyPIFallback,\n mountDrive,\n });\n },\n });\n },\n};\nconst plugins = [kernel];\nexport default plugins;\n","import { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { PathExt } from '@jupyterlab/coreutils';\nimport { MIME, FILE } from './tokens';\nimport { PromiseDelegate } from '@lumino/coreutils';\n/**\n * The name of the local storage.\n */\nconst DEFAULT_STORAGE_NAME = 'JupyterLite Storage';\n/**\n * The number of checkpoints to save.\n */\nconst N_CHECKPOINTS = 5;\n/**\n * A class to handle requests to /api/contents\n */\nexport class Contents {\n /**\n * Construct a new localForage-powered contents provider\n */\n constructor(options) {\n /**\n * A reducer for turning arbitrary binary into a string\n */\n this.reduceBytesToString = (data, byte) => {\n return data + String.fromCharCode(byte);\n };\n this._serverContents = new Map();\n this._storageName = DEFAULT_STORAGE_NAME;\n this._storageDrivers = null;\n this._localforage = options.localforage;\n this._storageName = options.storageName || DEFAULT_STORAGE_NAME;\n this._storageDrivers = options.storageDrivers || null;\n this._ready = new PromiseDelegate();\n }\n /**\n * Finish any initialization after server has started and all extensions are applied.\n */\n async initialize() {\n await this.initStorage();\n this._ready.resolve(void 0);\n }\n /**\n * Initialize all storage instances\n */\n async initStorage() {\n this._storage = this.createDefaultStorage();\n this._counters = this.createDefaultCounters();\n this._checkpoints = this.createDefaultCheckpoints();\n }\n /**\n * A promise that resolves once all storage is fully initialized.\n */\n get ready() {\n return this._ready.promise;\n }\n /**\n * A lazy reference to the underlying storage.\n */\n get storage() {\n return this.ready.then(() => this._storage);\n }\n /**\n * A lazy reference to the underlying counters.\n */\n get counters() {\n return this.ready.then(() => this._counters);\n }\n /**\n * A lazy reference to the underlying checkpoints.\n */\n get checkpoints() {\n return this.ready.then(() => this._checkpoints);\n }\n /**\n * Get default options for localForage instances\n */\n get defaultStorageOptions() {\n const driver = this._storageDrivers && this._storageDrivers.length ? this._storageDrivers : null;\n return {\n version: 1,\n name: this._storageName,\n ...(driver ? { driver } : {}),\n };\n }\n /**\n * Initialize the default storage for contents.\n */\n createDefaultStorage() {\n return this._localforage.createInstance({\n description: 'Offline Storage for Notebooks and Files',\n storeName: 'files',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Initialize the default storage for counting file suffixes.\n */\n createDefaultCounters() {\n return this._localforage.createInstance({\n description: 'Store the current file suffix counters',\n storeName: 'counters',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Create the default checkpoint storage.\n */\n createDefaultCheckpoints() {\n return this._localforage.createInstance({\n description: 'Offline Storage for Checkpoints',\n storeName: 'checkpoints',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the file is created.\n */\n async newUntitled(options) {\n var _a, _b, _c;\n const path = (_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : '';\n const type = (_b = options === null || options === void 0 ? void 0 : options.type) !== null && _b !== void 0 ? _b : 'notebook';\n const created = new Date().toISOString();\n let dirname = PathExt.dirname(path);\n const basename = PathExt.basename(path);\n const extname = PathExt.extname(path);\n const item = await this.get(dirname);\n // handle the case of \"Save As\", where the path points to the new file\n // to create, e.g. subfolder/example-copy.ipynb\n let name = '';\n if (path && !extname && item) {\n // directory\n dirname = `${path}/`;\n name = '';\n }\n else if (dirname && basename) {\n // file in a subfolder\n dirname = `${dirname}/`;\n name = basename;\n }\n else {\n // file at the top level\n dirname = '';\n name = path;\n }\n let file;\n switch (type) {\n case 'directory': {\n const counter = await this._incrementCounter('directory');\n name = `Untitled Folder${counter || ''}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: '',\n content: null,\n size: 0,\n writable: true,\n type: 'directory',\n };\n break;\n }\n case 'notebook': {\n const counter = await this._incrementCounter('notebook');\n name = name || `Untitled${counter || ''}.ipynb`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: MIME.JSON,\n content: Private.EMPTY_NB,\n size: JSON.stringify(Private.EMPTY_NB).length,\n writable: true,\n type: 'notebook',\n };\n break;\n }\n default: {\n const ext = (_c = options === null || options === void 0 ? void 0 : options.ext) !== null && _c !== void 0 ? _c : '.txt';\n const counter = await this._incrementCounter('file');\n const mimetype = FILE.getType(ext) || MIME.OCTET_STREAM;\n let format;\n if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n format = 'text';\n }\n else if (ext.indexOf('json') !== -1 || ext.indexOf('ipynb') !== -1) {\n format = 'json';\n }\n else {\n format = 'base64';\n }\n name = name || `untitled${counter || ''}${ext}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format,\n mimetype,\n content: '',\n size: 0,\n writable: true,\n type: 'file',\n };\n break;\n }\n }\n const key = file.path;\n await (await this.storage).setItem(key, file);\n return file;\n }\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n async copy(path, toDir) {\n let name = PathExt.basename(path);\n toDir = toDir === '' ? '' : `${toDir.slice(1)}/`;\n // TODO: better handle naming collisions with existing files\n while (await this.get(`${toDir}${name}`, { content: true })) {\n const ext = PathExt.extname(name);\n const base = name.replace(ext, '');\n name = `${base} (copy)${ext}`;\n }\n const toPath = `${toDir}${name}`;\n let item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n item = {\n ...item,\n name,\n path: toPath,\n };\n await (await this.storage).setItem(toPath, item);\n return item;\n }\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n async get(path, options) {\n // remove leading slash\n path = decodeURIComponent(path.replace(/^\\//, ''));\n if (path === '') {\n return await this._getFolder(path);\n }\n const storage = await this.storage;\n const item = await storage.getItem(path);\n const serverItem = await this._getServerContents(path, options);\n const model = (item || serverItem);\n if (!model) {\n return null;\n }\n if (!(options === null || options === void 0 ? void 0 : options.content)) {\n return {\n size: 0,\n ...model,\n content: null,\n };\n }\n // for directories, find all files with the path as the prefix\n if (model.type === 'directory') {\n const contentMap = new Map();\n await storage.iterate((file, key) => {\n // use an additional slash to not include the directory itself\n if (key === `${path}/${file.name}`) {\n contentMap.set(file.name, file);\n }\n });\n const serverContents = serverItem\n ? serverItem.content\n : Array.from((await this._getServerDirectory(path)).values());\n for (const file of serverContents) {\n if (!contentMap.has(file.name)) {\n contentMap.set(file.name, file);\n }\n }\n const content = [...contentMap.values()];\n return {\n name: PathExt.basename(path),\n path,\n last_modified: model.last_modified,\n created: model.created,\n format: 'json',\n mimetype: MIME.JSON,\n content,\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n return model;\n }\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the file is renamed.\n */\n async rename(oldLocalPath, newLocalPath) {\n const path = decodeURIComponent(oldLocalPath);\n const file = await this.get(path, { content: true });\n if (!file) {\n throw Error(`Could not find file with path ${path}`);\n }\n const modified = new Date().toISOString();\n const name = PathExt.basename(newLocalPath);\n const newFile = {\n ...file,\n name,\n path: newLocalPath,\n last_modified: modified,\n };\n const storage = await this.storage;\n await storage.setItem(newLocalPath, newFile);\n // remove the old file\n await storage.removeItem(path);\n // remove the corresponding checkpoint\n await (await this.checkpoints).removeItem(path);\n // if a directory, recurse through all children\n if (file.type === 'directory') {\n let child;\n for (child of file.content) {\n await this.rename(URLExt.join(oldLocalPath, child.name), URLExt.join(newLocalPath, child.name));\n }\n }\n return newFile;\n }\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the file is saved.\n */\n async save(path, options = {}) {\n var _a;\n path = decodeURIComponent(path);\n // process the file if coming from an upload\n const ext = PathExt.extname((_a = options.name) !== null && _a !== void 0 ? _a : '');\n const chunk = options.chunk;\n // retrieve the content if it is a later chunk or the last one\n // the new content will then be appended to the existing one\n const chunked = chunk ? chunk > 1 || chunk === -1 : false;\n let item = await this.get(path, { content: chunked });\n if (!item) {\n item = await this.newUntitled({ path, ext, type: 'file' });\n }\n if (!item) {\n return null;\n }\n // keep a reference to the original content\n const originalContent = item.content;\n const modified = new Date().toISOString();\n // override with the new values\n item = {\n ...item,\n ...options,\n last_modified: modified,\n };\n if (options.content && options.format === 'base64') {\n const lastChunk = chunk ? chunk === -1 : true;\n if (ext === '.ipynb') {\n const content = this._handleChunk(options.content, originalContent, chunked);\n item = {\n ...item,\n content: lastChunk ? JSON.parse(content) : content,\n format: 'json',\n type: 'notebook',\n size: content.length,\n };\n }\n else if (FILE.hasFormat(ext, 'json')) {\n const content = this._handleChunk(options.content, originalContent, chunked);\n item = {\n ...item,\n content: lastChunk ? JSON.parse(content) : content,\n format: 'json',\n type: 'file',\n size: content.length,\n };\n }\n else if (FILE.hasFormat(ext, 'text')) {\n const content = this._handleChunk(options.content, originalContent, chunked);\n item = {\n ...item,\n content,\n format: 'text',\n type: 'file',\n size: content.length,\n };\n }\n else {\n const content = options.content;\n item = {\n ...item,\n content,\n size: atob(content).length,\n };\n }\n }\n await (await this.storage).setItem(path, item);\n return item;\n }\n /**\n * Delete a file from browser storage.\n *\n * Has no effect on server-backed files, which will re-appear with their\n * original timestamp.\n *\n * @param path - The path to the file.\n */\n async delete(path) {\n path = decodeURIComponent(path);\n const slashed = `${path}/`;\n const toDelete = (await (await this.storage).keys()).filter((key) => key === path || key.startsWith(slashed));\n await Promise.all(toDelete.map(this.forgetPath, this));\n }\n /**\n * Remove the localForage and checkpoints for a path.\n *\n * @param path - The path to the file\n */\n async forgetPath(path) {\n await Promise.all([\n (await this.storage).removeItem(path),\n (await this.checkpoints).removeItem(path),\n ]);\n }\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n async createCheckpoint(path) {\n var _a;\n const checkpoints = await this.checkpoints;\n path = decodeURIComponent(path);\n const item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n const copies = ((_a = (await checkpoints.getItem(path))) !== null && _a !== void 0 ? _a : []).filter(Boolean);\n copies.push(item);\n // keep only a certain amount of checkpoints per file\n if (copies.length > N_CHECKPOINTS) {\n copies.splice(0, copies.length - N_CHECKPOINTS);\n }\n await checkpoints.setItem(path, copies);\n const id = `${copies.length - 1}`;\n return { id, last_modified: item.last_modified };\n }\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n async listCheckpoints(path) {\n const copies = (await (await this.checkpoints).getItem(path)) || [];\n return copies.filter(Boolean).map(this.normalizeCheckpoint, this);\n }\n normalizeCheckpoint(model, id) {\n return { id: id.toString(), last_modified: model.last_modified };\n }\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n async restoreCheckpoint(path, checkpointID) {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []);\n const id = parseInt(checkpointID);\n const item = copies[id];\n await (await this.storage).setItem(path, item);\n }\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n async deleteCheckpoint(path, checkpointID) {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []);\n const id = parseInt(checkpointID);\n copies.splice(id, 1);\n await (await this.checkpoints).setItem(path, copies);\n }\n /**\n * Handle a chunk of a file.\n * Decode and unescape a base64-encoded string.\n * @param content the content to process\n *\n * @returns the decoded string, appended to the original content if chunked\n * /\n */\n _handleChunk(newContent, originalContent, chunked) {\n const escaped = decodeURIComponent(escape(atob(newContent)));\n const content = chunked ? originalContent + escaped : escaped;\n return content;\n }\n /**\n * retrieve the contents for this path from the union of local storage and\n * `api/contents/{path}/all.json`.\n *\n * @param path - The contents path to retrieve\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n async _getFolder(path) {\n const content = new Map();\n const storage = await this.storage;\n await storage.iterate((file, key) => {\n if (key.includes('/')) {\n return;\n }\n content.set(file.path, file);\n });\n // layer in contents that don't have local overwrites\n for (const file of (await this._getServerDirectory(path)).values()) {\n if (!content.has(file.path)) {\n content.set(file.path, file);\n }\n }\n if (path && content.size === 0) {\n return null;\n }\n return {\n name: '',\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'json',\n mimetype: MIME.JSON,\n content: Array.from(content.values()),\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n /**\n * Attempt to recover the model from `{:path}/__all__.json` file, fall back to\n * deriving the model (including content) off the file in `/files/`. Otherwise\n * return `null`.\n */\n async _getServerContents(path, options) {\n const name = PathExt.basename(path);\n const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));\n let model = parentContents.get(name);\n if (!model) {\n return null;\n }\n model = model || {\n name,\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'text',\n mimetype: MIME.PLAIN_TEXT,\n type: 'file',\n writable: true,\n size: 0,\n content: '',\n };\n if (options === null || options === void 0 ? void 0 : options.content) {\n if (model.type === 'directory') {\n const serverContents = await this._getServerDirectory(path);\n model = { ...model, content: Array.from(serverContents.values()) };\n }\n else {\n const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);\n const response = await fetch(fileUrl);\n if (!response.ok) {\n return null;\n }\n const mimetype = model.mimetype || response.headers.get('Content-Type');\n const ext = PathExt.extname(name);\n if (model.type === 'notebook' ||\n FILE.hasFormat(ext, 'json') ||\n (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||\n path.match(/\\.(ipynb|[^/]*json[^/]*)$/)) {\n const contentText = await response.text();\n model = {\n ...model,\n content: JSON.parse(contentText),\n format: 'json',\n mimetype: model.mimetype || MIME.JSON,\n size: contentText.length,\n };\n }\n else if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n const contentText = await response.text();\n model = {\n ...model,\n content: contentText,\n format: 'text',\n mimetype: mimetype || MIME.PLAIN_TEXT,\n size: contentText.length,\n };\n }\n else {\n const contentBytes = await response.arrayBuffer();\n const contentBuffer = new Uint8Array(contentBytes);\n model = {\n ...model,\n content: btoa(contentBuffer.reduce(this.reduceBytesToString, '')),\n format: 'base64',\n mimetype: mimetype || MIME.OCTET_STREAM,\n size: contentBuffer.length,\n };\n }\n }\n }\n return model;\n }\n /**\n * retrieve the contents for this path from `__index__.json` in the appropriate\n * folder.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n async _getServerDirectory(path) {\n const content = this._serverContents.get(path) || new Map();\n if (!this._serverContents.has(path)) {\n const apiURL = URLExt.join(PageConfig.getBaseUrl(), 'api/contents', path, 'all.json');\n try {\n const response = await fetch(apiURL);\n const json = JSON.parse(await response.text());\n for (const file of json['content']) {\n content.set(file.name, file);\n }\n }\n catch (err) {\n console.warn(`don't worry, about ${err}... nothing's broken. If there had been a\n file at ${apiURL}, you might see some more files.`);\n }\n this._serverContents.set(path, content);\n }\n return content;\n }\n /**\n * Increment the counter for a given file type.\n * Used to avoid collisions when creating new untitled files.\n *\n * @param type The file type to increment the counter for.\n */\n async _incrementCounter(type) {\n var _a;\n const counters = await this.counters;\n const current = (_a = (await counters.getItem(type))) !== null && _a !== void 0 ? _a : -1;\n const counter = current + 1;\n await counters.setItem(type, counter);\n return counter;\n }\n}\n/**\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * The content for an empty notebook.\n */\n Private.EMPTY_NB = {\n metadata: {\n orig_nbformat: 4,\n },\n nbformat_minor: 4,\n nbformat: 4,\n cells: [],\n };\n})(Private || (Private = {}));\n//# sourceMappingURL=contents.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/// \nexport const DIR_MODE = 16895; // 040777\nexport const FILE_MODE = 33206; // 100666\nexport const SEEK_CUR = 1;\nexport const SEEK_END = 2;\n//# sourceMappingURL=emscripten.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n// Types and implementation inspired from https://github.com/jvilk/BrowserFS\n// LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE\n// And from https://github.com/gzuidhof/starboard-notebook\n// LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE\nimport { DIR_MODE, SEEK_CUR, SEEK_END, } from './emscripten';\nexport const DRIVE_SEPARATOR = ':';\nexport const DRIVE_API_PATH = '/api/drive.v1';\nexport const BLOCK_SIZE = 4096;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n// Mapping flag -> do we need to overwrite the file upon closing it\nconst flagNeedsWrite = {\n 0 /*O_RDONLY*/: false,\n 1 /*O_WRONLY*/: true,\n 2 /*O_RDWR*/: true,\n 64 /*O_CREAT*/: true,\n 65 /*O_WRONLY|O_CREAT*/: true,\n 66 /*O_RDWR|O_CREAT*/: true,\n 129 /*O_WRONLY|O_EXCL*/: true,\n 193 /*O_WRONLY|O_CREAT|O_EXCL*/: true,\n 514 /*O_RDWR|O_TRUNC*/: true,\n 577 /*O_WRONLY|O_CREAT|O_TRUNC*/: true,\n 578 /*O_CREAT|O_RDWR|O_TRUNC*/: true,\n 705 /*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 706 /*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 1024 /*O_APPEND*/: true,\n 1025 /*O_WRONLY|O_APPEND*/: true,\n 1026 /*O_RDWR|O_APPEND*/: true,\n 1089 /*O_WRONLY|O_CREAT|O_APPEND*/: true,\n 1090 /*O_RDWR|O_CREAT|O_APPEND*/: true,\n 1153 /*O_WRONLY|O_EXCL|O_APPEND*/: true,\n 1154 /*O_RDWR|O_EXCL|O_APPEND*/: true,\n 1217 /*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: true,\n 1218 /*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: true,\n 4096 /*O_RDONLY|O_DSYNC*/: true,\n 4098 /*O_RDWR|O_DSYNC*/: true,\n};\nexport class DriveFSEmscriptenStreamOps {\n constructor(fs) {\n this.fs = fs;\n }\n open(stream) {\n const path = this.fs.realPath(stream.node);\n if (this.fs.FS.isFile(stream.node.mode)) {\n stream.file = this.fs.API.get(path);\n }\n }\n close(stream) {\n if (!this.fs.FS.isFile(stream.node.mode) || !stream.file) {\n return;\n }\n const path = this.fs.realPath(stream.node);\n const flags = stream.flags;\n let parsedFlags = typeof flags === 'string' ? parseInt(flags, 10) : flags;\n parsedFlags &= 0x1fff;\n let needsWrite = true;\n if (parsedFlags in flagNeedsWrite) {\n needsWrite = flagNeedsWrite[parsedFlags];\n }\n if (needsWrite) {\n this.fs.API.put(path, stream.file);\n }\n stream.file = undefined;\n }\n read(stream, buffer, offset, length, position) {\n if (length <= 0 ||\n stream.file === undefined ||\n position >= (stream.file.data.length || 0)) {\n return 0;\n }\n const size = Math.min(stream.file.data.length - position, length);\n buffer.set(stream.file.data.subarray(position, position + size), offset);\n return size;\n }\n write(stream, buffer, offset, length, position) {\n var _a;\n if (length <= 0 || stream.file === undefined) {\n return 0;\n }\n stream.node.timestamp = Date.now();\n if (position + length > (((_a = stream.file) === null || _a === void 0 ? void 0 : _a.data.length) || 0)) {\n const oldData = stream.file.data ? stream.file.data : new Uint8Array();\n stream.file.data = new Uint8Array(position + length);\n stream.file.data.set(oldData);\n }\n stream.file.data.set(buffer.subarray(offset, offset + length), position);\n return length;\n }\n llseek(stream, offset, whence) {\n let position = offset;\n if (whence === SEEK_CUR) {\n position += stream.position;\n }\n else if (whence === SEEK_END) {\n if (this.fs.FS.isFile(stream.node.mode)) {\n if (stream.file !== undefined) {\n position += stream.file.data.length;\n }\n else {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM);\n }\n }\n }\n if (position < 0) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EINVAL);\n }\n return position;\n }\n}\nexport class DriveFSEmscriptenNodeOps {\n constructor(fs) {\n this.fs = fs;\n }\n getattr(node) {\n return {\n ...this.fs.API.getattr(this.fs.realPath(node)),\n mode: node.mode,\n ino: node.id,\n };\n }\n setattr(node, attr) {\n for (const [key, value] of Object.entries(attr)) {\n switch (key) {\n case 'mode':\n node.mode = value;\n break;\n case 'timestamp':\n node.timestamp = value;\n break;\n default:\n console.warn('setattr', key, 'of', value, 'on', node, 'not yet implemented');\n break;\n }\n }\n }\n lookup(parent, name) {\n const path = this.fs.PATH.join2(this.fs.realPath(parent), name);\n const result = this.fs.API.lookup(path);\n if (!result.ok) {\n throw this.fs.FS.genericErrors[this.fs.ERRNO_CODES['ENOENT']];\n }\n return this.fs.createNode(parent, name, result.mode, 0);\n }\n mknod(parent, name, mode, dev) {\n const path = this.fs.PATH.join2(this.fs.realPath(parent), name);\n this.fs.API.mknod(path, mode);\n return this.fs.createNode(parent, name, mode, dev);\n }\n rename(oldNode, newDir, newName) {\n this.fs.API.rename(oldNode.parent\n ? this.fs.PATH.join2(this.fs.realPath(oldNode.parent), oldNode.name)\n : oldNode.name, this.fs.PATH.join2(this.fs.realPath(newDir), newName));\n // Updating the in-memory node\n oldNode.name = newName;\n oldNode.parent = newDir;\n }\n unlink(parent, name) {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(parent), name));\n }\n rmdir(parent, name) {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(parent), name));\n }\n readdir(node) {\n return this.fs.API.readdir(this.fs.realPath(node));\n }\n symlink(parent, newName, oldPath) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n readlink(node) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n}\n/**\n * Wrap ServiceWorker requests for an Emscripten-compatible synchronous API.\n */\nexport class ContentsAPI {\n constructor(baseUrl, driveName, mountpoint, FS, ERRNO_CODES) {\n this._baseUrl = baseUrl;\n this._driveName = driveName;\n this._mountpoint = mountpoint;\n this.FS = FS;\n this.ERRNO_CODES = ERRNO_CODES;\n }\n request(data) {\n const xhr = new XMLHttpRequest();\n xhr.open('POST', encodeURI(this.endpoint), false);\n try {\n xhr.send(JSON.stringify(data));\n }\n catch (e) {\n console.error(e);\n }\n if (xhr.status >= 400) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n return JSON.parse(xhr.responseText);\n }\n lookup(path) {\n return this.request({ method: 'lookup', path: this.normalizePath(path) });\n }\n getmode(path) {\n return Number.parseInt(this.request({ method: 'getmode', path: this.normalizePath(path) }));\n }\n mknod(path, mode) {\n return this.request({\n method: 'mknod',\n path: this.normalizePath(path),\n data: { mode },\n });\n }\n rename(oldPath, newPath) {\n return this.request({\n method: 'rename',\n path: this.normalizePath(oldPath),\n data: { newPath: this.normalizePath(newPath) },\n });\n }\n readdir(path) {\n const dirlist = this.request({\n method: 'readdir',\n path: this.normalizePath(path),\n });\n dirlist.push('.');\n dirlist.push('..');\n return dirlist;\n }\n rmdir(path) {\n return this.request({ method: 'rmdir', path: this.normalizePath(path) });\n }\n get(path) {\n const response = this.request({ method: 'get', path: this.normalizePath(path) });\n const serializedContent = response.content;\n const format = response.format;\n switch (format) {\n case 'json':\n case 'text':\n return {\n data: encoder.encode(serializedContent),\n format,\n };\n case 'base64': {\n const binString = atob(serializedContent);\n const len = binString.length;\n const data = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n data[i] = binString.charCodeAt(i);\n }\n return {\n data,\n format,\n };\n }\n default:\n throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);\n }\n }\n put(path, value) {\n switch (value.format) {\n case 'json':\n case 'text':\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: decoder.decode(value.data),\n },\n });\n case 'base64': {\n let binary = '';\n for (let i = 0; i < value.data.byteLength; i++) {\n binary += String.fromCharCode(value.data[i]);\n }\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: btoa(binary),\n },\n });\n }\n }\n }\n getattr(path) {\n const stats = this.request({\n method: 'getattr',\n path: this.normalizePath(path),\n });\n // Turn datetimes into proper objects\n stats.atime = new Date(stats.atime);\n stats.mtime = new Date(stats.mtime);\n stats.ctime = new Date(stats.ctime);\n // ensure a non-undefined size (0 isn't great, though)\n stats.size = stats.size || 0;\n return stats;\n }\n /**\n * Normalize a Path by making it compliant for the content manager\n *\n * @param path: the path relatively to the Emscripten drive\n */\n normalizePath(path) {\n // Remove mountpoint prefix\n if (path.startsWith(this._mountpoint)) {\n path = path.slice(this._mountpoint.length);\n }\n // Add JupyterLab drive name\n if (this._driveName) {\n path = `${this._driveName}${DRIVE_SEPARATOR}${path}`;\n }\n return path;\n }\n /**\n * Get the api/drive endpoint\n */\n get endpoint() {\n return `${this._baseUrl}api/drive`;\n }\n}\nexport class DriveFS {\n constructor(options) {\n this.FS = options.FS;\n this.PATH = options.PATH;\n this.ERRNO_CODES = options.ERRNO_CODES;\n this.API = new ContentsAPI(options.baseUrl, options.driveName, options.mountpoint, this.FS, this.ERRNO_CODES);\n this.driveName = options.driveName;\n this.node_ops = new DriveFSEmscriptenNodeOps(this);\n this.stream_ops = new DriveFSEmscriptenStreamOps(this);\n }\n mount(mount) {\n return this.createNode(null, mount.mountpoint, DIR_MODE | 511, 0);\n }\n createNode(parent, name, mode, dev) {\n const FS = this.FS;\n if (!FS.isDir(mode) && !FS.isFile(mode)) {\n throw new FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n const node = FS.createNode(parent, name, mode, dev);\n node.node_ops = this.node_ops;\n node.stream_ops = this.stream_ops;\n return node;\n }\n getMode(path) {\n return this.API.getmode(path);\n }\n realPath(node) {\n const parts = [];\n let currentNode = node;\n parts.push(currentNode.name);\n while (currentNode.parent !== currentNode) {\n currentNode = currentNode.parent;\n parts.push(currentNode.name);\n }\n parts.reverse();\n return this.PATH.join.apply(null, parts);\n }\n}\n//# sourceMappingURL=drivefs.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { PathExt } from '@jupyterlab/coreutils';\nimport { DIR_MODE, FILE_MODE } from './emscripten';\nimport { BLOCK_SIZE, DRIVE_API_PATH } from './drivefs';\n/** A broadcaster for the ServiceWorker */\nexport class BroadcastChannelWrapper {\n constructor(options) {\n this.isDisposed = false;\n /** Handle a message received on the BroadcastChannel */\n this._onMessage = async (event) => {\n if (!this._channel) {\n return;\n }\n const { _contents } = this;\n const request = event.data;\n const path = request === null || request === void 0 ? void 0 : request.path;\n const receiver = request === null || request === void 0 ? void 0 : request.receiver;\n if (receiver !== 'broadcast.ts') {\n // Message is not meant for us\n return;\n }\n // many successful responses default to null\n let response = null;\n // most requests will use a model\n let model;\n switch (request === null || request === void 0 ? void 0 : request.method) {\n case 'readdir':\n model = await _contents.get(path, { content: true });\n response = [];\n if (model.type === 'directory' && model.content) {\n response = model.content.map((subcontent) => subcontent.name);\n }\n break;\n case 'rmdir':\n await _contents.delete(path);\n break;\n case 'rename':\n await _contents.rename(path, request.data.newPath);\n break;\n case 'getmode':\n model = await _contents.get(path);\n if (model.type === 'directory') {\n response = DIR_MODE;\n }\n else {\n response = FILE_MODE;\n }\n break;\n case 'lookup':\n try {\n model = await _contents.get(path);\n response = {\n ok: true,\n mode: model.type === 'directory' ? DIR_MODE : FILE_MODE,\n };\n }\n catch (e) {\n response = { ok: false };\n }\n break;\n case 'mknod':\n model = await _contents.newUntitled({\n path: PathExt.dirname(path),\n type: Number.parseInt(request.data.mode) === DIR_MODE ? 'directory' : 'file',\n ext: PathExt.extname(path),\n });\n await _contents.rename(model.path, path);\n break;\n case 'getattr': {\n model = await _contents.get(path);\n // create a default date for drives that send incomplete information\n // for nested foldes and files\n const defaultDate = new Date(0).toISOString();\n response = {\n dev: 1,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n size: model.size || 0,\n blksize: BLOCK_SIZE,\n blocks: Math.ceil(model.size || 0 / BLOCK_SIZE),\n atime: model.last_modified || defaultDate,\n mtime: model.last_modified || defaultDate,\n ctime: model.created || defaultDate,\n timestamp: 0,\n };\n break;\n }\n case 'get':\n model = await _contents.get(path, { content: true });\n if (model.type === 'directory') {\n break;\n }\n response = {\n content: model.format === 'json' ? JSON.stringify(model.content) : model.content,\n format: model.format,\n };\n break;\n case 'put':\n await _contents.save(path, {\n content: request.data.format === 'json'\n ? JSON.parse(request.data.data)\n : request.data.data,\n type: 'file',\n format: request.data.format,\n });\n break;\n default:\n response = null;\n break;\n }\n this._channel.postMessage(response);\n };\n this._channel = null;\n this._enabled = false;\n this._contents = options.contents;\n }\n get enabled() {\n return this._enabled;\n }\n enable() {\n if (this._channel) {\n console.warn('BroadcastChannel already created and enabled');\n return;\n }\n this._channel = new BroadcastChannel(DRIVE_API_PATH);\n this._channel.addEventListener('message', this._onMessage);\n this._enabled = true;\n }\n disable() {\n if (this._channel) {\n this._channel.removeEventListener('message', this._onMessage);\n this._channel = null;\n }\n this._enabled = false;\n }\n /** Clean up the broadcaster. */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this.disable();\n this.isDisposed = true;\n }\n}\n//# sourceMappingURL=broadcast.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Signal } from '@lumino/signaling';\n/**\n * A concrete implementation of IObservableMap.\n */\nexport class ObservableMap {\n /**\n * Construct a new observable map.\n */\n constructor(options = {}) {\n this._map = new Map();\n this._changed = new Signal(this);\n this._isDisposed = false;\n this._itemCmp = options.itemCmp || Private.itemCmp;\n if (options.values) {\n for (const key in options.values) {\n this._map.set(key, options.values[key]);\n }\n }\n }\n /**\n * The type of the Observable.\n */\n get type() {\n return 'Map';\n }\n /**\n * A signal emitted when the map has changed.\n */\n get changed() {\n return this._changed;\n }\n /**\n * Whether this map has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * The number of key-value pairs in the map.\n */\n get size() {\n return this._map.size;\n }\n /**\n * Set a key-value pair in the map\n *\n * @param key - The key to set.\n *\n * @param value - The value for the key.\n *\n * @returns the old value for the key, or undefined\n * if that did not exist.\n *\n * @throws if the new value is undefined.\n *\n * #### Notes\n * This is a no-op if the value does not change.\n */\n set(key, value) {\n const oldVal = this._map.get(key);\n if (value === undefined) {\n throw Error('Cannot set an undefined value, use remove');\n }\n // Bail if the value does not change.\n const itemCmp = this._itemCmp;\n if (oldVal !== undefined && itemCmp(oldVal, value)) {\n return oldVal;\n }\n this._map.set(key, value);\n this._changed.emit({\n type: oldVal ? 'change' : 'add',\n key: key,\n oldValue: oldVal,\n newValue: value\n });\n return oldVal;\n }\n /**\n * Get a value for a given key.\n *\n * @param key - the key.\n *\n * @returns the value for that key.\n */\n get(key) {\n return this._map.get(key);\n }\n /**\n * Check whether the map has a key.\n *\n * @param key - the key to check.\n *\n * @returns `true` if the map has the key, `false` otherwise.\n */\n has(key) {\n return this._map.has(key);\n }\n /**\n * Get a list of the keys in the map.\n *\n * @returns - a list of keys.\n */\n keys() {\n const keyList = [];\n this._map.forEach((v, k) => {\n keyList.push(k);\n });\n return keyList;\n }\n /**\n * Get a list of the values in the map.\n *\n * @returns - a list of values.\n */\n values() {\n const valList = [];\n this._map.forEach((v, k) => {\n valList.push(v);\n });\n return valList;\n }\n /**\n * Remove a key from the map\n *\n * @param key - the key to remove.\n *\n * @returns the value of the given key,\n * or undefined if that does not exist.\n *\n * #### Notes\n * This is a no-op if the value does not change.\n */\n delete(key) {\n const oldVal = this._map.get(key);\n const removed = this._map.delete(key);\n if (removed) {\n this._changed.emit({\n type: 'remove',\n key: key,\n oldValue: oldVal,\n newValue: undefined\n });\n }\n return oldVal;\n }\n /**\n * Set the ObservableMap to an empty map.\n */\n clear() {\n // Delete one by one to emit the correct signals.\n const keyList = this.keys();\n for (let i = 0; i < keyList.length; i++) {\n this.delete(keyList[i]);\n }\n }\n /**\n * Dispose of the resources held by the map.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n this._map.clear();\n }\n}\n/**\n * The namespace for module private data.\n */\nvar Private;\n(function (Private) {\n /**\n * The default strict equality item comparator.\n */\n function itemCmp(first, second) {\n return first === second;\n }\n Private.itemCmp = itemCmp;\n})(Private || (Private = {}));\n//# sourceMappingURL=observablemap.js.map","const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_maxConcurrency, _cancelError = E_CANCELED) {\n this._maxConcurrency = _maxConcurrency;\n this._cancelError = _cancelError;\n this._queue = [];\n this._waiters = [];\n if (_maxConcurrency <= 0) {\n throw new Error('semaphore must be initialized to a positive value');\n }\n this._value = _maxConcurrency;\n }\n acquire() {\n const locked = this.isLocked();\n const ticketPromise = new Promise((resolve, reject) => this._queue.push({ resolve, reject }));\n if (!locked)\n this._dispatch();\n return ticketPromise;\n }\n runExclusive(callback) {\n return __awaiter$2(this, void 0, void 0, function* () {\n const [value, release] = yield this.acquire();\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock() {\n return __awaiter$2(this, void 0, void 0, function* () {\n if (!this.isLocked()) {\n return Promise.resolve();\n }\n const waitPromise = new Promise((resolve) => this._waiters.push({ resolve }));\n return waitPromise;\n });\n }\n isLocked() {\n return this._value <= 0;\n }\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release() {\n if (this._maxConcurrency > 1) {\n throw new Error('this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead');\n }\n if (this._currentReleaser) {\n const releaser = this._currentReleaser;\n this._currentReleaser = undefined;\n releaser();\n }\n }\n cancel() {\n this._queue.forEach((ticket) => ticket.reject(this._cancelError));\n this._queue = [];\n }\n _dispatch() {\n const nextTicket = this._queue.shift();\n if (!nextTicket)\n return;\n let released = false;\n this._currentReleaser = () => {\n if (released)\n return;\n released = true;\n this._value++;\n this._resolveWaiters();\n this._dispatch();\n };\n nextTicket.resolve([this._value--, this._currentReleaser]);\n }\n _resolveWaiters() {\n this._waiters.forEach((waiter) => waiter.resolve());\n this._waiters = [];\n }\n}\n\nvar __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, void 0, void 0, function* () {\n const [, releaser] = yield this._semaphore.acquire();\n return releaser;\n });\n }\n runExclusive(callback) {\n return this._semaphore.runExclusive(() => callback());\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock() {\n return this._semaphore.waitForUnlock();\n }\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release() {\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: () => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield sync.acquire();\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n })),\n runExclusive(callback) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire();\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release() {\n sync.release();\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: () => sync.waitForUnlock(),\n isLocked: () => sync.isLocked(),\n };\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\nexport { E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Mutex, Semaphore, tryAcquire, withTimeout };\n","import { ObservableMap } from '@jupyterlab/observables';\nimport { deserialize, serialize } from '@jupyterlab/services/lib/kernel/serialize';\nimport { supportedKernelWebSocketProtocols } from '@jupyterlab/services/lib/kernel/messages';\nimport { UUID } from '@lumino/coreutils';\nimport { Server as WebSocketServer } from 'mock-socket';\nimport { Mutex } from 'async-mutex';\nimport { PageConfig } from '@jupyterlab/coreutils';\n/**\n * Use the default kernel wire protocol.\n */\nconst KERNEL_WEBSOCKET_PROTOCOL = supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg;\n/**\n * A class to handle requests to /api/kernels\n */\nexport class Kernels {\n /**\n * Construct a new Kernels\n *\n * @param options The instantiation options\n */\n constructor(options) {\n this._kernels = new ObservableMap();\n this._clients = new ObservableMap();\n this._kernelClients = new ObservableMap();\n const { kernelspecs } = options;\n this._kernelspecs = kernelspecs;\n }\n /**\n * Start a new kernel.\n *\n * @param options The kernel start options.\n */\n async startNew(options) {\n const { id, name, location } = options;\n const factory = this._kernelspecs.factories.get(name);\n // bail if there is no factory associated with the requested kernel\n if (!factory) {\n return { id, name };\n }\n // create a synchronization mechanism to allow only one message\n // to be processed at a time\n const mutex = new Mutex();\n // hook a new client to a kernel\n const hook = (kernelId, clientId, socket) => {\n var _a;\n const kernel = this._kernels.get(kernelId);\n if (!kernel) {\n throw Error(`No kernel ${kernelId}`);\n }\n this._clients.set(clientId, socket);\n (_a = this._kernelClients.get(kernelId)) === null || _a === void 0 ? void 0 : _a.add(clientId);\n const processMsg = async (msg) => {\n await mutex.runExclusive(async () => {\n await kernel.ready;\n await kernel.handleMessage(msg);\n });\n };\n socket.on('message', async (message) => {\n let msg;\n if (message instanceof ArrayBuffer) {\n message = new Uint8Array(message).buffer;\n msg = deserialize(message, KERNEL_WEBSOCKET_PROTOCOL);\n }\n else if (typeof message === 'string') {\n const encoder = new TextEncoder();\n const encodedData = encoder.encode(message);\n msg = deserialize(encodedData.buffer, KERNEL_WEBSOCKET_PROTOCOL);\n }\n else {\n return;\n }\n // TODO Find a better solution for this?\n // input-reply is asynchronous, must not be processed like other messages\n if (msg.header.msg_type === 'input_reply') {\n kernel.handleMessage(msg);\n }\n else {\n void processMsg(msg);\n }\n });\n const removeClient = () => {\n var _a;\n this._clients.delete(clientId);\n (_a = this._kernelClients.get(kernelId)) === null || _a === void 0 ? void 0 : _a.delete(clientId);\n };\n kernel.disposed.connect(removeClient);\n // TODO: check whether this is called\n // https://github.com/thoov/mock-socket/issues/298\n // https://github.com/jupyterlab/jupyterlab/blob/6bc884a7a8ed73c615ce72ba097bdb790482b5bf/packages/services/src/kernel/default.ts#L1245\n socket.onclose = removeClient;\n };\n // ensure kernel id\n const kernelId = id !== null && id !== void 0 ? id : UUID.uuid4();\n // There is one server per kernel which handles multiple clients\n const kernelUrl = `${Kernels.WS_BASE_URL}api/kernels/${kernelId}/channels`;\n const runningKernel = this._kernels.get(kernelId);\n if (runningKernel) {\n return {\n id: runningKernel.id,\n name: runningKernel.name,\n };\n }\n // start the kernel\n const sendMessage = (msg) => {\n const clientId = msg.header.session;\n const socket = this._clients.get(clientId);\n if (!socket) {\n console.warn(`Trying to send message on removed socket for kernel ${kernelId}`);\n return;\n }\n const message = serialize(msg, KERNEL_WEBSOCKET_PROTOCOL);\n // process iopub messages\n if (msg.channel === 'iopub') {\n const clients = this._kernelClients.get(kernelId);\n clients === null || clients === void 0 ? void 0 : clients.forEach((id) => {\n var _a;\n (_a = this._clients.get(id)) === null || _a === void 0 ? void 0 : _a.send(message);\n });\n return;\n }\n socket.send(message);\n };\n const kernel = await factory({\n id: kernelId,\n sendMessage,\n name,\n location,\n });\n this._kernels.set(kernelId, kernel);\n this._kernelClients.set(kernelId, new Set());\n // create the websocket server for the kernel\n const wsServer = new WebSocketServer(kernelUrl, {\n mock: false,\n selectProtocol: () => KERNEL_WEBSOCKET_PROTOCOL,\n });\n wsServer.on('connection', (socket) => {\n var _a;\n const url = new URL(socket.url);\n const clientId = (_a = url.searchParams.get('session_id')) !== null && _a !== void 0 ? _a : '';\n hook(kernelId, clientId, socket);\n });\n // clean up closed connection\n wsServer.on('close', () => {\n this._clients.keys().forEach((clientId) => {\n var _a;\n const socket = this._clients.get(clientId);\n if ((socket === null || socket === void 0 ? void 0 : socket.readyState) === WebSocket.CLOSED) {\n this._clients.delete(clientId);\n (_a = this._kernelClients.get(kernelId)) === null || _a === void 0 ? void 0 : _a.delete(clientId);\n }\n });\n });\n // cleanup on kernel shutdown\n kernel.disposed.connect(() => {\n wsServer.close();\n this._kernels.delete(kernelId);\n this._kernelClients.delete(kernelId);\n });\n return {\n id: kernel.id,\n name: kernel.name,\n };\n }\n /**\n * Restart a kernel.\n *\n * @param kernelId The kernel id.\n */\n async restart(kernelId) {\n const kernel = this._kernels.get(kernelId);\n if (!kernel) {\n throw Error(`Kernel ${kernelId} does not exist`);\n }\n const { id, name, location } = kernel;\n kernel.dispose();\n return this.startNew({ id, name, location });\n }\n /**\n * List the running kernels.\n */\n async list() {\n return [...this._kernels.values()].map((kernel) => ({\n id: kernel.id,\n name: kernel.name,\n }));\n }\n /**\n * Shut down a kernel.\n *\n * @param id The kernel id.\n */\n async shutdown(id) {\n var _a;\n (_a = this._kernels.delete(id)) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n /**\n * Get a kernel by id\n */\n async get(id) {\n return this._kernels.get(id);\n }\n}\n/**\n * A namespace for Kernels statics.\n */\n(function (Kernels) {\n /**\n * The base url for the Kernels manager\n */\n Kernels.WS_BASE_URL = PageConfig.getBaseUrl().replace(/^http/, 'ws');\n})(Kernels || (Kernels = {}));\n//# sourceMappingURL=kernels.js.map","import { PageConfig } from '@jupyterlab/coreutils';\nimport { FALLBACK_KERNEL } from './tokens';\n/**\n * A class to handle requests to /api/kernelspecs\n */\nexport class KernelSpecs {\n constructor() {\n this._specs = new Map();\n this._factories = new Map();\n }\n /**\n * Get the kernel specs.\n */\n get specs() {\n if (this._specs.size === 0) {\n return null;\n }\n return {\n default: this.defaultKernelName,\n kernelspecs: Object.fromEntries(this._specs),\n };\n }\n /**\n * Get the default kernel name.\n */\n get defaultKernelName() {\n let defaultKernelName = PageConfig.getOption('defaultKernelName');\n if (!defaultKernelName && this._specs.size) {\n const keys = Array.from(this._specs.keys());\n keys.sort();\n defaultKernelName = keys[0];\n }\n return defaultKernelName || FALLBACK_KERNEL;\n }\n /**\n * Get the kernel factories for the current kernels.\n */\n get factories() {\n return this._factories;\n }\n /**\n * Register a new kernel.\n *\n * @param options The options to register a new kernel.\n */\n register(options) {\n const { spec, create } = options;\n this._specs.set(spec.name, spec);\n this._factories.set(spec.name, create);\n }\n}\n//# sourceMappingURL=kernelspecs.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Token } from '@lumino/coreutils';\n/**\n * The well-known name of the file. Can actually be configured by alternate\n * implementations, but the default is probably good enough for \"best-effort.\"\n */\nexport const THIRD_PARTY_LICENSES = 'third-party-licenses.json';\n/**\n * The token for the licenses service.\n */\nexport const ILicenses = new Token('@jupyterlite/licenses:ILicenses');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { URLExt, PageConfig } from '@jupyterlab/coreutils';\nimport { THIRD_PARTY_LICENSES, } from './tokens';\n/**\n * An empty bundle.\n */\nconst EMPTY_BUNDLE = Object.freeze({ packages: [] });\n/**\n * A JupyterLite implementation of the jupyterlab_server licenses route\n */\nexport class Licenses {\n /**\n * A GET handler for the licenses\n */\n async get() {\n return {\n bundles: {\n ...(await this._getFederated()),\n [this.appName]: await this._getAppLicenses(),\n },\n };\n }\n /**\n * Get the app name (or default).\n */\n get appName() {\n return PageConfig.getOption('appName') || 'JupyterLite';\n }\n /**\n * Get the well-known URL of the app licenses.\n */\n get appLicensesUrl() {\n return URLExt.join(PageConfig.getBaseUrl(), 'build', THIRD_PARTY_LICENSES);\n }\n /**\n * Get the lab extension base url.\n */\n get labExtensionsUrl() {\n return PageConfig.getOption('fullLabextensionsUrl');\n }\n /**\n * Resolve the licenses for the app distribution itself, or the empty bundle.\n */\n async _getAppLicenses() {\n let bundle = EMPTY_BUNDLE;\n try {\n const response = await fetch(this.appLicensesUrl);\n bundle = response.json();\n }\n catch (err) {\n console.warn('Could not resolve licenses for', this.appName);\n }\n return bundle;\n }\n /**\n * Resolve the licenses for all federated extensions.\n */\n async _getFederated() {\n const bundles = {};\n let federated;\n try {\n federated = JSON.parse(PageConfig.getOption('federated_extensions'));\n }\n catch {\n return bundles;\n }\n const promises = [];\n for (const ext of federated) {\n promises.push(this._getOneFederated(ext, bundles));\n }\n try {\n await Promise.all(promises);\n }\n catch (err) {\n console.warn('Error resolving licenses', err);\n }\n return bundles;\n }\n /**\n * Update the bundles with the extension's licenses, or the empty bundle.\n */\n async _getOneFederated(ext, bundles) {\n try {\n const url = URLExt.join(this.labExtensionsUrl, ext.name, 'static', THIRD_PARTY_LICENSES);\n const response = await fetch(url);\n bundles[ext.name] = await response.json();\n }\n catch {\n console.warn('Could not resolve licenses for', ext);\n bundles[ext.name] = EMPTY_BUNDLE;\n }\n }\n}\n//# sourceMappingURL=licenses.js.map","import { Token } from '@lumino/coreutils';\n/**\n * The token for the sessions service.\n */\nexport const ISessions = new Token('@jupyterlite/session:ISessions');\n//# sourceMappingURL=tokens.js.map","import { PathExt } from '@jupyterlab/coreutils';\nimport { ArrayExt } from '@lumino/algorithm';\nimport { UUID } from '@lumino/coreutils';\n/**\n * A class to handle requests to /api/sessions\n */\nexport class Sessions {\n /**\n * Construct a new Sessions.\n *\n * @param options The instantiation options for a Sessions.\n */\n constructor(options) {\n // TODO: offload to a database\n this._sessions = [];\n this._kernels = options.kernels;\n }\n /**\n * Get a session by id.\n *\n * @param id The id of the session.\n */\n async get(id) {\n const session = this._sessions.find((s) => s.id === id);\n if (!session) {\n throw Error(`Session ${id} not found`);\n }\n return session;\n }\n /**\n * List the running sessions\n */\n async list() {\n return this._sessions;\n }\n /**\n * Path an existing session.\n * This can be used to rename a session.\n *\n * - path updates session to track renamed paths\n * - kernel.name starts a new kernel with a given kernelspec\n *\n * @param options The options to patch the session.\n */\n async patch(options) {\n const { id, path, name, kernel } = options;\n const index = this._sessions.findIndex((s) => s.id === id);\n const session = this._sessions[index];\n if (!session) {\n throw Error(`Session ${id} not found`);\n }\n const patched = {\n ...session,\n path: path !== null && path !== void 0 ? path : session.path,\n name: name !== null && name !== void 0 ? name : session.name,\n };\n if (kernel) {\n // Kernel id takes precedence over name.\n if (kernel.id) {\n const session = this._sessions.find((session) => { var _a; return ((_a = session.kernel) === null || _a === void 0 ? void 0 : _a.id) === (kernel === null || kernel === void 0 ? void 0 : kernel.id); });\n if (session) {\n patched.kernel = session.kernel;\n }\n }\n else if (kernel.name) {\n const newKernel = await this._kernels.startNew({\n id: UUID.uuid4(),\n name: kernel.name,\n location: PathExt.dirname(patched.path),\n });\n if (newKernel) {\n patched.kernel = newKernel;\n }\n // clean up the session on kernel shutdown\n void this._handleKernelShutdown({\n kernelId: newKernel.id,\n sessionId: session.id,\n });\n }\n }\n this._sessions[index] = patched;\n return patched;\n }\n /**\n * Start a new session\n * TODO: read path and name\n *\n * @param options The options to start a new session.\n */\n async startNew(options) {\n var _a, _b, _c, _d;\n const { path, name } = options;\n const running = this._sessions.find((s) => s.name === name);\n if (running) {\n return running;\n }\n const kernelName = (_b = (_a = options.kernel) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : '';\n const id = (_c = options.id) !== null && _c !== void 0 ? _c : UUID.uuid4();\n const nameOrPath = (_d = options.name) !== null && _d !== void 0 ? _d : options.path;\n const dirname = PathExt.dirname(options.name) || PathExt.dirname(options.path);\n const hasDrive = nameOrPath.includes(':');\n const driveName = hasDrive ? nameOrPath.split(':')[0] : '';\n // add drive name if missing (top level directory)\n const location = dirname.includes(driveName) ? dirname : `${driveName}:${dirname}`;\n const kernel = await this._kernels.startNew({\n id,\n name: kernelName,\n location,\n });\n const session = {\n id,\n path,\n name: name !== null && name !== void 0 ? name : path,\n type: 'notebook',\n kernel: {\n id: kernel.id,\n name: kernel.name,\n },\n };\n this._sessions.push(session);\n // clean up the session on kernel shutdown\n void this._handleKernelShutdown({ kernelId: id, sessionId: session.id });\n return session;\n }\n /**\n * Shut down a session.\n *\n * @param id The id of the session to shut down.\n */\n async shutdown(id) {\n var _a;\n const session = this._sessions.find((s) => s.id === id);\n if (!session) {\n throw Error(`Session ${id} not found`);\n }\n const kernelId = (_a = session.kernel) === null || _a === void 0 ? void 0 : _a.id;\n if (kernelId) {\n await this._kernels.shutdown(kernelId);\n }\n ArrayExt.removeFirstOf(this._sessions, session);\n }\n /**\n * Handle kernel shutdown\n */\n async _handleKernelShutdown({ kernelId, sessionId, }) {\n const runningKernel = await this._kernels.get(kernelId);\n if (runningKernel) {\n runningKernel.disposed.connect(() => {\n this.shutdown(sessionId);\n });\n }\n }\n}\n//# sourceMappingURL=sessions.js.map","import { Token } from '@lumino/coreutils';\n/**\n * The token for the settings service.\n */\nexport const ISettings = new Token('@jupyterlite/settings:ISettings');\n//# sourceMappingURL=tokens.js.map","import { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport * as json5 from 'json5';\n/**\n * The name of the local storage.\n */\nconst DEFAULT_STORAGE_NAME = 'JupyterLite Storage';\n/**\n * A class to handle requests to /api/settings\n */\nexport class Settings {\n constructor(options) {\n this._storageName = DEFAULT_STORAGE_NAME;\n this._storageDrivers = null;\n this._localforage = options.localforage;\n this._storageName = options.storageName || DEFAULT_STORAGE_NAME;\n this._storageDrivers = options.storageDrivers || null;\n this._ready = new PromiseDelegate();\n }\n /**\n * A promise that resolves when the settings storage is fully initialized\n */\n get ready() {\n return this._ready.promise;\n }\n /**\n * A lazy reference to initialized storage\n */\n get storage() {\n return this.ready.then(() => this._storage);\n }\n /**\n * Finish any initialization after server has started and all extensions are applied.\n */\n async initialize() {\n await this.initStorage();\n this._ready.resolve(void 0);\n }\n /**\n * Prepare the storage\n */\n async initStorage() {\n this._storage = this.defaultSettingsStorage();\n }\n /**\n * Get default options for localForage instances\n */\n get defaultStorageOptions() {\n var _a;\n const driver = ((_a = this._storageDrivers) === null || _a === void 0 ? void 0 : _a.length) ? this._storageDrivers : null;\n return {\n version: 1,\n name: this._storageName,\n ...(driver ? { driver } : {}),\n };\n }\n /**\n * Create a settings store.\n */\n defaultSettingsStorage() {\n return this._localforage.createInstance({\n description: 'Offline Storage for Settings',\n storeName: 'settings',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Get settings by plugin id\n *\n * @param pluginId the id of the plugin\n *\n */\n async get(pluginId) {\n const all = await this.getAll();\n const settings = all.settings;\n const setting = settings.find((setting) => {\n return setting.id === pluginId;\n });\n return setting;\n }\n /**\n * Get all the settings\n */\n async getAll() {\n const [allCore, allFederated] = await Promise.all([\n this._getAll('all.json'),\n this._getAll('all_federated.json'),\n ]);\n // JupyterLab 4 expects all settings to be returned in one go\n // so append the settings from federated plugins to the core ones\n const all = allCore.concat(allFederated);\n // return existing user settings if they exist\n const storage = await this.storage;\n const settings = await Promise.all(all.map(async (plugin) => {\n var _a;\n const { id } = plugin;\n const raw = (_a = (await storage.getItem(id))) !== null && _a !== void 0 ? _a : plugin.raw;\n return {\n ...Private.override(plugin),\n raw,\n settings: json5.parse(raw),\n };\n }));\n return { settings };\n }\n /**\n * Save settings for a given plugin id\n *\n * @param pluginId The id of the plugin\n * @param raw The raw settings\n *\n */\n async save(pluginId, raw) {\n await (await this.storage).setItem(pluginId, raw);\n }\n /**\n * Get all the settings for core or federated plugins\n */\n async _getAll(file) {\n var _a;\n const settingsUrl = (_a = PageConfig.getOption('settingsUrl')) !== null && _a !== void 0 ? _a : '/';\n const all = (await (await fetch(URLExt.join(settingsUrl, file))).json());\n return all;\n }\n}\n/**\n * A namespace for private data\n */\nvar Private;\n(function (Private) {\n const _overrides = JSON.parse(PageConfig.getOption('settingsOverrides') || '{}');\n /**\n * Override the defaults of the schema with ones from PageConfig\n *\n * @see https://github.com/jupyterlab/jupyterlab_server/blob/v2.5.2/jupyterlab_server/settings_handler.py#L216-L227\n */\n function override(plugin) {\n if (_overrides[plugin.id]) {\n if (!plugin.schema.properties) {\n // probably malformed, or only provides keyboard shortcuts, etc.\n plugin.schema.properties = {};\n }\n for (const [prop, propDefault] of Object.entries(_overrides[plugin.id] || {})) {\n plugin.schema.properties[prop].default = propDefault;\n }\n }\n return plugin;\n }\n Private.override = override;\n})(Private || (Private = {}));\n//# sourceMappingURL=settings.js.map","import { Token } from '@lumino/coreutils';\n/**\n * The token for the settings service.\n */\nexport const ITranslation = new Token('@jupyterlite/translation:ITranslation');\n//# sourceMappingURL=tokens.js.map","import { PageConfig, URLExt } from '@jupyterlab/coreutils';\n/**\n * A fake locale to retrieve all the language packs.\n */\nconst ALL = 'all';\n/**\n * A class to handle requests to /api/translations\n */\nexport class Translation {\n constructor() {\n this._prevLocale = '';\n }\n /**\n * Get the translation data for the given locale\n * @param locale The locale\n * @returns\n */\n async get(locale) {\n const apiURL = URLExt.join(PageConfig.getBaseUrl(), `api/translations/${locale}.json`);\n try {\n const response = await fetch(apiURL);\n const json = JSON.parse(await response.text());\n if (this._prevLocale !== ALL && locale === ALL) {\n // TODO: fix this logic upstream?\n // the upstream translation plugin relies on the comparison between\n // the display name and the native name to enable or disable the commands:\n // https://github.com/jupyterlab/jupyterlab/blob/befa831ffef36321b87f352a48fbe2439df6c872/packages/translation-extension/src/index.ts#L117\n const prev = this._prevLocale;\n json.data[prev].displayName = json.data[prev].nativeName;\n if (prev !== 'en') {\n json.data['en'].displayName = `${json.data['en'].nativeName} (default)`;\n }\n }\n this._prevLocale = locale;\n return json;\n }\n catch (e) {\n if (locale) {\n return {\n data: {},\n message: `Language pack '${locale}' not installed!`,\n };\n }\n return {\n data: {\n en: { displayName: 'English', nativeName: 'English' },\n },\n message: '',\n };\n }\n }\n}\n//# sourceMappingURL=translation.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Token } from '@lumino/coreutils';\n/**\n * The token for the localforage singleton.\n */\nexport const ILocalForage = new Token('@jupyterlite/localforge:ILocalForage');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport { BroadcastChannelWrapper, Contents, IContents, IBroadcastChannelWrapper, } from '@jupyterlite/contents';\nimport { IKernels, Kernels, IKernelSpecs, KernelSpecs } from '@jupyterlite/kernel';\nimport { ILicenses, Licenses } from '@jupyterlite/licenses';\nimport { IServiceWorkerManager, ServiceWorkerManager, } from '@jupyterlite/server';\nimport { ISessions, Sessions } from '@jupyterlite/session';\nimport { ISettings, Settings } from '@jupyterlite/settings';\nimport { ITranslation, Translation } from '@jupyterlite/translation';\nimport { ILocalForage, ensureMemoryStorage } from '@jupyterlite/localforage';\nimport localforage from 'localforage';\n/**\n * The localforage plugin\n */\nconst localforagePlugin = {\n id: '@jupyterlite/server-extension:localforage',\n autoStart: true,\n provides: ILocalForage,\n activate: (app) => {\n return { localforage };\n },\n};\n/**\n * The volatile localforage memory plugin\n */\nconst localforageMemoryPlugin = {\n id: '@jupyterlite/server-extension:localforage-memory-storage',\n autoStart: true,\n requires: [ILocalForage],\n activate: async (app, forage) => {\n if (JSON.parse(PageConfig.getOption('enableMemoryStorage') || 'false')) {\n console.warn('Memory storage fallback enabled: contents and settings may not be saved');\n await ensureMemoryStorage(forage.localforage);\n }\n },\n};\n/**\n * The contents service plugin.\n */\nconst contentsPlugin = {\n id: '@jupyterlite/server-extension:contents',\n requires: [ILocalForage],\n autoStart: true,\n provides: IContents,\n activate: (app, forage) => {\n const storageName = PageConfig.getOption('contentsStorageName');\n const storageDrivers = JSON.parse(PageConfig.getOption('contentsStorageDrivers') || 'null');\n const { localforage } = forage;\n const contents = new Contents({\n storageName,\n storageDrivers,\n localforage,\n });\n app.started.then(() => contents.initialize().catch(console.warn));\n return contents;\n },\n};\n/**\n * A plugin providing the routes for the contents service.\n */\nconst contentsRoutesPlugin = {\n id: '@jupyterlite/server-extension:contents-routes',\n autoStart: true,\n requires: [IContents],\n activate: (app, contents) => {\n // GET /api/contents/{path}/checkpoints - Get a list of checkpoints for a file\n app.router.get('/api/contents/(.+)/checkpoints', async (req, filename) => {\n const res = await contents.listCheckpoints(filename);\n return new Response(JSON.stringify(res));\n });\n // POST /api/contents/{path}/checkpoints/{checkpoint_id} - Restore a file to a particular checkpointed state\n app.router.post('/api/contents/(.+)/checkpoints/(.*)', async (req, filename, checkpoint) => {\n const res = await contents.restoreCheckpoint(filename, checkpoint);\n return new Response(JSON.stringify(res), { status: 204 });\n });\n // POST /api/contents/{path}/checkpoints - Create a new checkpoint for a file\n app.router.post('/api/contents/(.+)/checkpoints', async (req, filename) => {\n const res = await contents.createCheckpoint(filename);\n return new Response(JSON.stringify(res), { status: 201 });\n });\n // DELETE /api/contents/{path}/checkpoints/{checkpoint_id} - Delete a checkpoint\n app.router.delete('/api/contents/(.+)/checkpoints/(.*)', async (req, filename, checkpoint) => {\n const res = await contents.deleteCheckpoint(filename, checkpoint);\n return new Response(JSON.stringify(res), { status: 204 });\n });\n // GET /api/contents/{path} - Get contents of file or directory\n app.router.get('/api/contents(.*)', async (req, filename) => {\n var _a;\n const options = {\n content: ((_a = req.query) === null || _a === void 0 ? void 0 : _a.content) === '1',\n };\n const nb = await contents.get(filename, options);\n if (!nb) {\n return new Response(null, { status: 404 });\n }\n return new Response(JSON.stringify(nb));\n });\n // POST /api/contents/{path} - Create a new file in the specified path\n app.router.post('/api/contents(.*)', async (req, path) => {\n const options = req.body;\n const copyFrom = options === null || options === void 0 ? void 0 : options.copy_from;\n let file;\n if (copyFrom) {\n file = await contents.copy(copyFrom, path);\n }\n else {\n file = await contents.newUntitled(options);\n }\n if (!file) {\n return new Response(null, { status: 400 });\n }\n return new Response(JSON.stringify(file), { status: 201 });\n });\n // PATCH /api/contents/{path} - Rename a file or directory without re-uploading content\n app.router.patch('/api/contents(.*)', async (req, filename) => {\n var _a, _b;\n const newPath = (_b = (_a = req.body) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : '';\n filename = filename[0] === '/' ? filename.slice(1) : filename;\n const nb = await contents.rename(filename, newPath);\n return new Response(JSON.stringify(nb));\n });\n // PUT /api/contents/{path} - Save or upload a file\n app.router.put('/api/contents/(.+)', async (req, filename) => {\n const body = req.body;\n const nb = await contents.save(filename, body);\n return new Response(JSON.stringify(nb));\n });\n // DELETE /api/contents/{path} - Delete a file in the given path\n app.router.delete('/api/contents/(.+)', async (req, filename) => {\n await contents.delete(filename);\n return new Response(null, { status: 204 });\n });\n },\n};\n/**\n * A plugin installing the service worker.\n */\nconst serviceWorkerPlugin = {\n id: '@jupyterlite/server-extension:service-worker',\n autoStart: true,\n provides: IServiceWorkerManager,\n activate: (app) => {\n return new ServiceWorkerManager();\n },\n};\n/**\n * A plugin for handling communication with the Emscpriten file system.\n */\nconst emscriptenFileSystemPlugin = {\n id: '@jupyterlite/server-extension:emscripten-filesystem',\n autoStart: true,\n optional: [IServiceWorkerManager],\n provides: IBroadcastChannelWrapper,\n activate: (app, serviceWorkerRegistrationWrapper) => {\n const { contents } = app.serviceManager;\n const broadcaster = new BroadcastChannelWrapper({ contents });\n const what = 'Kernel filesystem and JupyterLite contents';\n function logStatus(msg, err) {\n if (err) {\n console.warn(err);\n }\n if (msg) {\n console.warn(msg);\n }\n if (err || msg) {\n console.warn(`${what} will NOT be synced`);\n }\n else {\n console.info(`${what} will be synced`);\n }\n }\n if (!serviceWorkerRegistrationWrapper) {\n logStatus('JupyterLite ServiceWorker not available');\n }\n else {\n serviceWorkerRegistrationWrapper.ready\n .then(() => {\n broadcaster.enable();\n logStatus();\n })\n .catch((err) => {\n logStatus('JupyterLite ServiceWorker failed to become available', err);\n });\n }\n return broadcaster;\n },\n};\n/**\n * The kernels service plugin.\n */\nconst kernelsPlugin = {\n id: '@jupyterlite/server-extension:kernels',\n autoStart: true,\n provides: IKernels,\n requires: [IKernelSpecs],\n activate: (app, kernelspecs) => {\n return new Kernels({ kernelspecs });\n },\n};\n/**\n * A plugin providing the routes for the kernels service\n */\nconst kernelsRoutesPlugin = {\n id: '@jupyterlite/server-extension:kernels-routes',\n autoStart: true,\n requires: [IKernels],\n activate: (app, kernels) => {\n // GET /api/kernels - List the running kernels\n app.router.get('/api/kernels', async (req) => {\n const res = await kernels.list();\n return new Response(JSON.stringify(res));\n });\n // POST /api/kernels/{kernel_id} - Restart a kernel\n app.router.post('/api/kernels/(.*)/restart', async (req, kernelId) => {\n const res = await kernels.restart(kernelId);\n return new Response(JSON.stringify(res));\n });\n // DELETE /api/kernels/{kernel_id} - Kill a kernel and delete the kernel id\n app.router.delete('/api/kernels/(.*)', async (req, kernelId) => {\n const res = await kernels.shutdown(kernelId);\n return new Response(JSON.stringify(res), { status: 204 });\n });\n },\n};\n/**\n * The kernel spec service plugin.\n */\nconst kernelSpecPlugin = {\n id: '@jupyterlite/server-extension:kernelspec',\n autoStart: true,\n provides: IKernelSpecs,\n activate: (app) => {\n return new KernelSpecs();\n },\n};\n/**\n * A plugin providing the routes for the kernelspec service.\n */\nconst kernelSpecRoutesPlugin = {\n id: '@jupyterlite/server-extension:kernelspec-routes',\n autoStart: true,\n requires: [IKernelSpecs],\n activate: (app, kernelspecs) => {\n app.router.get('/api/kernelspecs', async (req) => {\n const { specs } = kernelspecs;\n if (!specs) {\n return new Response(null);\n }\n // follow the same format as in Jupyter Server\n const allKernelSpecs = {};\n const allSpecs = specs.kernelspecs;\n Object.keys(allSpecs).forEach((name) => {\n const spec = allSpecs[name];\n const { resources } = spec !== null && spec !== void 0 ? spec : {};\n allKernelSpecs[name] = {\n name,\n spec,\n resources,\n };\n });\n const res = {\n default: specs.default,\n kernelspecs: allKernelSpecs,\n };\n return new Response(JSON.stringify(res));\n });\n },\n};\n/**\n * The licenses service plugin\n */\nconst licensesPlugin = {\n id: '@jupyterlite/server-extension:licenses',\n autoStart: true,\n provides: ILicenses,\n activate: (app) => {\n return new Licenses();\n },\n};\n/**\n * A plugin providing the routes for the licenses service.\n */\nconst licensesRoutesPlugin = {\n id: '@jupyterlite/server-extension:licenses-routes',\n autoStart: true,\n requires: [ILicenses],\n activate(app, licenses) {\n app.router.get('/api/licenses', async (req) => {\n const res = await licenses.get();\n return new Response(JSON.stringify(res));\n });\n },\n};\n/**\n * A plugin providing the routes for the lsp service.\n * TODO: provide the service in a separate plugin?\n */\nconst lspRoutesPlugin = {\n id: '@jupyterlite/server-extension:lsp-routes',\n autoStart: true,\n activate: (app) => {\n app.router.get('/lsp/status', async (req) => {\n return new Response(JSON.stringify({ version: 2, sessions: {}, specs: {} }));\n });\n },\n};\n/**\n * A plugin providing the routes for the nbconvert service.\n * TODO: provide the service in a separate plugin?\n */\nconst nbconvertRoutesPlugin = {\n id: '@jupyterlite/server-extension:nbconvert-routes',\n autoStart: true,\n activate: (app) => {\n app.router.get('/api/nbconvert', async (req) => {\n return new Response(JSON.stringify({}));\n });\n },\n};\n/**\n * The sessions service plugin.\n */\nconst sessionsPlugin = {\n id: '@jupyterlite/server-extension:sessions',\n autoStart: true,\n provides: ISessions,\n requires: [IKernels],\n activate: (app, kernels) => {\n return new Sessions({ kernels });\n },\n};\n/**\n * A plugin providing the routes for the session service.\n */\nconst sessionsRoutesPlugin = {\n id: '@jupyterlite/server-extension:sessions-routes',\n autoStart: true,\n requires: [ISessions],\n activate: (app, sessions) => {\n // GET /api/sessions/{session} - Get session\n app.router.get('/api/sessions/(.+)', async (req, id) => {\n const session = await sessions.get(id);\n return new Response(JSON.stringify(session), { status: 200 });\n });\n // GET /api/sessions - List available sessions\n app.router.get('/api/sessions', async (req) => {\n const list = await sessions.list();\n return new Response(JSON.stringify(list), { status: 200 });\n });\n // PATCH /api/sessions/{session} - This can be used to rename a session\n app.router.patch('/api/sessions(.*)', async (req, id) => {\n const options = req.body;\n const session = await sessions.patch(options);\n return new Response(JSON.stringify(session), { status: 200 });\n });\n // DELETE /api/sessions/{session} - Delete a session\n app.router.delete('/api/sessions/(.+)', async (req, id) => {\n await sessions.shutdown(id);\n return new Response(null, { status: 204 });\n });\n // POST /api/sessions - Create a new session or return an existing session if a session of the same name already exists\n app.router.post('/api/sessions', async (req) => {\n const options = req.body;\n const session = await sessions.startNew(options);\n return new Response(JSON.stringify(session), { status: 201 });\n });\n },\n};\n/**\n * The settings service plugin.\n */\nconst settingsPlugin = {\n id: '@jupyterlite/server-extension:settings',\n autoStart: true,\n requires: [ILocalForage],\n provides: ISettings,\n activate: (app, forage) => {\n const storageName = PageConfig.getOption('settingsStorageName');\n const storageDrivers = JSON.parse(PageConfig.getOption('settingsStorageDrivers') || 'null');\n const { localforage } = forage;\n const settings = new Settings({ storageName, storageDrivers, localforage });\n app.started.then(() => settings.initialize().catch(console.warn));\n return settings;\n },\n};\n/**\n * A plugin providing the routes for the settings service.\n */\nconst settingsRoutesPlugin = {\n id: '@jupyterlite/server-extension:settings-routes',\n autoStart: true,\n requires: [ISettings],\n activate: (app, settings) => {\n // TODO: improve the regex\n // const pluginPattern = new RegExp(/(?:@([^/]+?)[/])?([^/]+?):(\\w+)/);\n const pluginPattern = '/api/settings/((?:@([^/]+?)[/])?([^/]+?):([^:]+))$';\n app.router.get(pluginPattern, async (req, pluginId) => {\n const setting = await settings.get(pluginId);\n return new Response(JSON.stringify(setting));\n });\n app.router.put(pluginPattern, async (req, pluginId) => {\n const body = req.body;\n const { raw } = body;\n await settings.save(pluginId, raw);\n return new Response(null, { status: 204 });\n });\n app.router.get('/api/settings', async (req) => {\n const plugins = await settings.getAll();\n return new Response(JSON.stringify(plugins));\n });\n },\n};\n/**\n * The translation service plugin.\n */\nconst translationPlugin = {\n id: '@jupyterlite/server-extension:translation',\n autoStart: true,\n provides: ITranslation,\n activate: (app) => {\n const translation = new Translation();\n app.router.get('/api/translations/?(.*)', async (req, locale) => {\n if (locale === 'default') {\n locale = 'en';\n }\n const data = await translation.get(locale || 'all');\n return new Response(JSON.stringify(data));\n });\n return translation;\n },\n};\n/**\n * A plugin providing the routes for the translation service.\n */\nconst translationRoutesPlugin = {\n id: '@jupyterlite/server-extension:translation-routes',\n autoStart: true,\n requires: [ITranslation],\n activate: (app, translation) => {\n app.router.get('/api/translations/?(.*)', async (req, locale) => {\n const data = await translation.get(locale || 'all');\n return new Response(JSON.stringify(data));\n });\n },\n};\nconst plugins = [\n contentsPlugin,\n contentsRoutesPlugin,\n emscriptenFileSystemPlugin,\n kernelsPlugin,\n kernelsRoutesPlugin,\n kernelSpecPlugin,\n kernelSpecRoutesPlugin,\n licensesPlugin,\n licensesRoutesPlugin,\n localforageMemoryPlugin,\n localforagePlugin,\n lspRoutesPlugin,\n nbconvertRoutesPlugin,\n serviceWorkerPlugin,\n sessionsPlugin,\n sessionsRoutesPlugin,\n settingsPlugin,\n settingsRoutesPlugin,\n translationPlugin,\n translationRoutesPlugin,\n];\nexport default plugins;\n//# sourceMappingURL=index.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport memoryStorageDriver from 'localforage-memoryStorageDriver';\n/**\n * Ensure a localforage singleton has had the memory storage driver installed\n */\nexport async function ensureMemoryStorage(theLocalforage) {\n return await theLocalforage.defineDriver(memoryStorageDriver);\n}\n//# sourceMappingURL=memory.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2019, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for clipboard related functionality.\n */\nvar ClipboardExt;\n(function (ClipboardExt) {\n /**\n * Copy text to the system clipboard.\n *\n * @param text - The text to copy to the clipboard.\n */\n function copyText(text) {\n // Fetch the document body.\n const body = document.body;\n // Set up the clipboard event listener.\n const handler = (event) => {\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Set the clipboard data.\n event.clipboardData.setData('text', text);\n // Remove the event listener.\n body.removeEventListener('copy', handler, true);\n };\n // Add the event listener.\n body.addEventListener('copy', handler, true);\n // Trigger the event.\n document.execCommand('copy');\n }\n ClipboardExt.copyText = copyText;\n})(ClipboardExt || (ClipboardExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for element related utilities.\n */\nvar ElementExt;\n(function (ElementExt) {\n /**\n * Compute the box sizing for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The box sizing data for the specified element.\n */\n function boxSizing(element) {\n let style = window.getComputedStyle(element);\n let bt = parseFloat(style.borderTopWidth) || 0;\n let bl = parseFloat(style.borderLeftWidth) || 0;\n let br = parseFloat(style.borderRightWidth) || 0;\n let bb = parseFloat(style.borderBottomWidth) || 0;\n let pt = parseFloat(style.paddingTop) || 0;\n let pl = parseFloat(style.paddingLeft) || 0;\n let pr = parseFloat(style.paddingRight) || 0;\n let pb = parseFloat(style.paddingBottom) || 0;\n let hs = bl + pl + pr + br;\n let vs = bt + pt + pb + bb;\n return {\n borderTop: bt,\n borderLeft: bl,\n borderRight: br,\n borderBottom: bb,\n paddingTop: pt,\n paddingLeft: pl,\n paddingRight: pr,\n paddingBottom: pb,\n horizontalSum: hs,\n verticalSum: vs\n };\n }\n ElementExt.boxSizing = boxSizing;\n /**\n * Compute the size limits for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The size limit data for the specified element.\n */\n function sizeLimits(element) {\n let style = window.getComputedStyle(element);\n let minWidth = parseFloat(style.minWidth) || 0;\n let minHeight = parseFloat(style.minHeight) || 0;\n let maxWidth = parseFloat(style.maxWidth) || Infinity;\n let maxHeight = parseFloat(style.maxHeight) || Infinity;\n maxWidth = Math.max(minWidth, maxWidth);\n maxHeight = Math.max(minHeight, maxHeight);\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n ElementExt.sizeLimits = sizeLimits;\n /**\n * Test whether a client position lies within an element.\n *\n * @param element - The DOM element of interest.\n *\n * @param clientX - The client X coordinate of interest.\n *\n * @param clientY - The client Y coordinate of interest.\n *\n * @returns Whether the point is within the given element.\n */\n function hitTest(element, clientX, clientY) {\n let rect = element.getBoundingClientRect();\n return (clientX >= rect.left &&\n clientX < rect.right &&\n clientY >= rect.top &&\n clientY < rect.bottom);\n }\n ElementExt.hitTest = hitTest;\n /**\n * Vertically scroll an element into view if needed.\n *\n * @param area - The scroll area element.\n *\n * @param element - The element of interest.\n *\n * #### Notes\n * This follows the \"nearest\" behavior of the native `scrollIntoView`\n * method, which is not supported by all browsers.\n * https://drafts.csswg.org/cssom-view/#element-scrolling-members\n *\n * If the element fully covers the visible area or is fully contained\n * within the visible area, no scrolling will take place. Otherwise,\n * the nearest edges of the area and element are aligned.\n */\n function scrollIntoViewIfNeeded(area, element) {\n let ar = area.getBoundingClientRect();\n let er = element.getBoundingClientRect();\n if (er.top <= ar.top && er.bottom >= ar.bottom) {\n return;\n }\n if (er.top < ar.top && er.height <= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.bottom > ar.bottom && er.height >= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.top < ar.top && er.height > ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n if (er.bottom > ar.bottom && er.height < ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n }\n ElementExt.scrollIntoViewIfNeeded = scrollIntoViewIfNeeded;\n})(ElementExt || (ElementExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for platform related utilities.\n */\nvar Platform;\n(function (Platform) {\n /**\n * A flag indicating whether the platform is Mac.\n */\n Platform.IS_MAC = !!navigator.platform.match(/Mac/i);\n /**\n * A flag indicating whether the platform is Windows.\n */\n Platform.IS_WIN = !!navigator.platform.match(/Win/i);\n /**\n * A flag indicating whether the browser is IE.\n */\n Platform.IS_IE = /Trident/.test(navigator.userAgent);\n /**\n * A flag indicating whether the browser is Edge.\n */\n Platform.IS_EDGE = /Edge/.test(navigator.userAgent);\n /**\n * Test whether the `accel` key is pressed.\n *\n * @param event - The keyboard or mouse event of interest.\n *\n * @returns Whether the `accel` key is pressed.\n *\n * #### Notes\n * On Mac the `accel` key is the command key. On all other\n * platforms the `accel` key is the control key.\n */\n function accelKey(event) {\n return Platform.IS_MAC ? event.metaKey : event.ctrlKey;\n }\n Platform.accelKey = accelKey;\n})(Platform || (Platform = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for selector related utilities.\n */\nvar Selector;\n(function (Selector) {\n /**\n * Calculate the specificity of a single CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns The specificity of the selector.\n *\n * #### Undefined Behavior\n * The selector is invalid.\n *\n * #### Notes\n * This is based on https://www.w3.org/TR/css3-selectors/#specificity\n *\n * A larger number represents a more specific selector.\n *\n * The smallest possible specificity is `0`.\n *\n * The result is represented as a hex number `0x` where\n * each component is the count of the respective selector clause.\n *\n * If the selector contains commas, only the first clause is used.\n *\n * The computed result is cached, so subsequent calculations for the\n * same selector are extremely fast.\n */\n function calculateSpecificity(selector) {\n if (selector in Private.specificityCache) {\n return Private.specificityCache[selector];\n }\n let result = Private.calculateSingle(selector);\n return (Private.specificityCache[selector] = result);\n }\n Selector.calculateSpecificity = calculateSpecificity;\n /**\n * Test whether a selector is a valid CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns `true` if the selector is valid, `false` otherwise.\n *\n * #### Notes\n * The computed result is cached, so subsequent tests for the same\n * selector are extremely fast.\n */\n function isValid(selector) {\n if (selector in Private.validityCache) {\n return Private.validityCache[selector];\n }\n let result = true;\n try {\n Private.testElem.querySelector(selector);\n }\n catch (err) {\n result = false;\n }\n return (Private.validityCache[selector] = result);\n }\n Selector.isValid = isValid;\n /**\n * Test whether an element matches a CSS selector.\n *\n * @param element - The element of interest.\n *\n * @param selector - The valid CSS selector of interest.\n *\n * @returns `true` if the element is a match, `false` otherwise.\n *\n * #### Notes\n * This function uses the builtin browser capabilities when possible,\n * falling back onto a document query otherwise.\n */\n function matches(element, selector) {\n return Private.protoMatchFunc.call(element, selector);\n }\n Selector.matches = matches;\n})(Selector || (Selector = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A cache of computed selector specificity values.\n */\n Private.specificityCache = Object.create(null);\n /**\n * A cache of computed selector validity.\n */\n Private.validityCache = Object.create(null);\n /**\n * An empty element for testing selector validity.\n */\n Private.testElem = document.createElement('div');\n /**\n * A cross-browser CSS selector matching prototype function.\n */\n Private.protoMatchFunc = (() => {\n let proto = Element.prototype;\n return (proto.matches ||\n proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector ||\n function (selector) {\n let elem = this;\n let matches = elem.ownerDocument\n ? elem.ownerDocument.querySelectorAll(selector)\n : [];\n return Array.prototype.indexOf.call(matches, elem) !== -1;\n });\n })();\n /**\n * Calculate the specificity of a single selector.\n *\n * The behavior is undefined if the selector is invalid.\n */\n function calculateSingle(selector) {\n // Ignore anything after the first comma.\n selector = selector.split(',', 1)[0];\n // Setup the aggregate counters.\n let a = 0;\n let b = 0;\n let c = 0;\n // Apply a regex to the front of the selector. If it succeeds, that\n // portion of the selector is removed. Returns a success/fail flag.\n function match(re) {\n let match = selector.match(re);\n if (match === null) {\n return false;\n }\n selector = selector.slice(match[0].length);\n return true;\n }\n // Replace the negation pseudo-class (which is ignored),\n // but keep its inner content (which is not ignored).\n selector = selector.replace(NEGATION_RE, ' $1 ');\n // Continue matching until the selector is consumed.\n while (selector.length > 0) {\n // Match an ID selector.\n if (match(ID_RE)) {\n a++;\n continue;\n }\n // Match a class selector.\n if (match(CLASS_RE)) {\n b++;\n continue;\n }\n // Match an attribute selector.\n if (match(ATTR_RE)) {\n b++;\n continue;\n }\n // Match a pseudo-element selector. This is done before matching\n // a pseudo-class since this regex overlaps with that regex.\n if (match(PSEUDO_ELEM_RE)) {\n c++;\n continue;\n }\n // Match a pseudo-class selector.\n if (match(PSEDUO_CLASS_RE)) {\n b++;\n continue;\n }\n // Match a plain type selector.\n if (match(TYPE_RE)) {\n c++;\n continue;\n }\n // Finally, match any ignored characters.\n if (match(IGNORE_RE)) {\n continue;\n }\n // At this point, the selector is assumed to be invalid.\n return 0;\n }\n // Clamp each component to a reasonable base.\n a = Math.min(a, 0xff);\n b = Math.min(b, 0xff);\n c = Math.min(c, 0xff);\n // Combine the components into a single result.\n return (a << 16) | (b << 8) | c;\n }\n Private.calculateSingle = calculateSingle;\n /**\n * A regex which matches an ID selector at string start.\n */\n const ID_RE = /^#[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a class selector at string start.\n */\n const CLASS_RE = /^\\.[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches an attribute selector at string start.\n */\n const ATTR_RE = /^\\[[^\\]]+\\]/;\n /**\n * A regex which matches a type selector at string start.\n */\n const TYPE_RE = /^[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a pseudo-element selector at string start.\n */\n const PSEUDO_ELEM_RE = /^(::[^\\s\\+>~#\\.\\[:]+|:first-line|:first-letter|:before|:after)/;\n /**\n * A regex which matches a pseudo-class selector at string start.\n */\n const PSEDUO_CLASS_RE = /^:[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches ignored characters at string start.\n */\n const IGNORE_RE = /^[\\s\\+>~\\*]+/;\n /**\n * A regex which matches the negation pseudo-class globally.\n */\n const NEGATION_RE = /:not\\(([^\\)]+)\\)/g;\n})(Private || (Private = {}));\n\nexport { ClipboardExt, ElementExt, Platform, Selector };\n//# sourceMappingURL=index.es6.js.map\n","import { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\n/**\n * A disposable object which delegates to a callback function.\n */\nclass DisposableDelegate {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn) {\n this._fn = fn;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return !this._fn;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n}\n/**\n * An observable disposable object which delegates to a callback function.\n */\nclass ObservableDisposableDelegate extends DisposableDelegate {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * An object which manages a collection of disposable items.\n */\nclass DisposableSet {\n constructor() {\n this._isDisposed = false;\n this._items = new Set();\n }\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item) {\n return this._items.has(item);\n }\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item) {\n this._items.add(item);\n }\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item) {\n this._items.delete(item);\n }\n /**\n * Remove all items from the set.\n */\n clear() {\n this._items.clear();\n }\n}\n/**\n * The namespace for the `DisposableSet` class statics.\n */\n(function (DisposableSet) {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n DisposableSet.from = from;\n})(DisposableSet || (DisposableSet = {}));\n/**\n * An observable object which manages a collection of disposable items.\n */\nclass ObservableDisposableSet extends DisposableSet {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\n(function (ObservableDisposableSet) {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n ObservableDisposableSet.from = from;\n})(ObservableDisposableSet || (ObservableDisposableSet = {}));\n\nexport { DisposableDelegate, DisposableSet, ObservableDisposableDelegate, ObservableDisposableSet };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module keyboard\n */\n/**\n * Get the global application keyboard layout instance.\n *\n * @returns The keyboard layout for use by the application.\n *\n * #### Notes\n * The default keyboard layout is US-English.\n */\nfunction getKeyboardLayout() {\n return Private.keyboardLayout;\n}\n/**\n * Set the global application keyboard layout instance.\n *\n * @param - The keyboard layout for use by the application.\n *\n * #### Notes\n * The keyboard layout should typically be set on application startup\n * to a layout which is appropriate for the user's system.\n */\nfunction setKeyboardLayout(layout) {\n Private.keyboardLayout = layout;\n}\n/**\n * A concrete implementation of {@link IKeyboardLayout} based on keycodes.\n *\n * The `keyCode` property of a `'keydown'` event is a browser and OS\n * specific representation of the physical key (not character) which\n * was pressed on a keyboard. While not the most convenient API, it\n * is currently the only one which works reliably on all browsers.\n *\n * This class accepts a user-defined mapping of keycode to key, which\n * allows for reliable shortcuts tailored to the user's system.\n */\nclass KeycodeLayout {\n /**\n * Construct a new keycode layout.\n *\n * @param name - The human readable name for the layout.\n *\n * @param codes - A mapping of keycode to key value.\n *\n * @param modifierKeys - Array of modifier key names\n */\n constructor(name, codes, modifierKeys = []) {\n this.name = name;\n this._codes = codes;\n this._keys = KeycodeLayout.extractKeys(codes);\n this._modifierKeys = KeycodeLayout.convertToKeySet(modifierKeys);\n }\n /**\n * Get an array of the key values supported by the layout.\n *\n * @returns A new array of the supported key values.\n */\n keys() {\n return Object.keys(this._keys);\n }\n /**\n * Test whether the given key is a valid value for the layout.\n *\n * @param key - The user provided key to test for validity.\n *\n * @returns `true` if the key is valid, `false` otherwise.\n */\n isValidKey(key) {\n return key in this._keys;\n }\n /**\n * Test whether the given key is a modifier key.\n *\n * @param key - The user provided key.\n *\n * @returns `true` if the key is a modifier key, `false` otherwise.\n */\n isModifierKey(key) {\n return key in this._modifierKeys;\n }\n /**\n * Get the key for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns The associated key value, or an empty string if\n * the event does not represent a valid primary key.\n */\n keyForKeydownEvent(event) {\n return this._codes[event.keyCode] || '';\n }\n}\n/**\n * The namespace for the `KeycodeLayout` class statics.\n */\n(function (KeycodeLayout) {\n /**\n * Extract the set of keys from a code map.\n *\n * @param code - The code map of interest.\n *\n * @returns A set of the keys in the code map.\n */\n function extractKeys(codes) {\n let keys = Object.create(null);\n for (let c in codes) {\n keys[codes[c]] = true;\n }\n return keys;\n }\n KeycodeLayout.extractKeys = extractKeys;\n /**\n * Convert array of keys to a key set.\n *\n * @param keys - The array that needs to be converted\n *\n * @returns A set of the keys in the array.\n */\n function convertToKeySet(keys) {\n let keySet = Object(null);\n for (let i = 0, n = keys.length; i < n; ++i) {\n keySet[keys[i]] = true;\n }\n return keySet;\n }\n KeycodeLayout.convertToKeySet = convertToKeySet;\n})(KeycodeLayout || (KeycodeLayout = {}));\n/**\n * A keycode-based keyboard layout for US English keyboards.\n *\n * This layout is valid for the following OS/Browser combinations.\n *\n * - Windows\n * - Chrome\n * - Firefox\n * - IE\n *\n * - OSX\n * - Chrome\n * - Firefox\n * - Safari\n *\n * - Linux\n * - Chrome\n * - Firefox\n *\n * Other combinations may also work, but are untested.\n */\nconst EN_US = new KeycodeLayout('en-us', {\n 8: 'Backspace',\n 9: 'Tab',\n 13: 'Enter',\n 16: 'Shift',\n 17: 'Ctrl',\n 18: 'Alt',\n 19: 'Pause',\n 27: 'Escape',\n 32: 'Space',\n 33: 'PageUp',\n 34: 'PageDown',\n 35: 'End',\n 36: 'Home',\n 37: 'ArrowLeft',\n 38: 'ArrowUp',\n 39: 'ArrowRight',\n 40: 'ArrowDown',\n 45: 'Insert',\n 46: 'Delete',\n 48: '0',\n 49: '1',\n 50: '2',\n 51: '3',\n 52: '4',\n 53: '5',\n 54: '6',\n 55: '7',\n 56: '8',\n 57: '9',\n 59: ';',\n 61: '=',\n 65: 'A',\n 66: 'B',\n 67: 'C',\n 68: 'D',\n 69: 'E',\n 70: 'F',\n 71: 'G',\n 72: 'H',\n 73: 'I',\n 74: 'J',\n 75: 'K',\n 76: 'L',\n 77: 'M',\n 78: 'N',\n 79: 'O',\n 80: 'P',\n 81: 'Q',\n 82: 'R',\n 83: 'S',\n 84: 'T',\n 85: 'U',\n 86: 'V',\n 87: 'W',\n 88: 'X',\n 89: 'Y',\n 90: 'Z',\n 91: 'Meta',\n 93: 'ContextMenu',\n 96: '0',\n 97: '1',\n 98: '2',\n 99: '3',\n 100: '4',\n 101: '5',\n 102: '6',\n 103: '7',\n 104: '8',\n 105: '9',\n 106: '*',\n 107: '+',\n 109: '-',\n 110: '.',\n 111: '/',\n 112: 'F1',\n 113: 'F2',\n 114: 'F3',\n 115: 'F4',\n 116: 'F5',\n 117: 'F6',\n 118: 'F7',\n 119: 'F8',\n 120: 'F9',\n 121: 'F10',\n 122: 'F11',\n 123: 'F12',\n 173: '-',\n 186: ';',\n 187: '=',\n 188: ',',\n 189: '-',\n 190: '.',\n 191: '/',\n 192: '`',\n 219: '[',\n 220: '\\\\',\n 221: ']',\n 222: \"'\",\n 224: 'Meta' // firefox\n}, ['Shift', 'Ctrl', 'Alt', 'Meta'] // modifier keys\n);\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The global keyboard layout instance.\n */\n Private.keyboardLayout = EN_US;\n})(Private || (Private = {}));\n\nexport { EN_US, KeycodeLayout, getKeyboardLayout, setKeyboardLayout };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt } from '@lumino/algorithm';\nimport { JSONExt } from '@lumino/coreutils';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport { Platform, Selector } from '@lumino/domutils';\nimport { getKeyboardLayout } from '@lumino/keyboard';\nimport { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module commands\n */\n/**\n * An object which manages a collection of commands.\n *\n * #### Notes\n * A command registry can be used to populate a variety of action-based\n * widgets, such as command palettes, menus, and toolbars.\n */\nclass CommandRegistry {\n constructor() {\n this._timerID = 0;\n this._replaying = false;\n this._keystrokes = [];\n this._keydownEvents = [];\n this._keyBindings = [];\n this._exactKeyMatch = null;\n this._commands = new Map();\n this._commandChanged = new Signal(this);\n this._commandExecuted = new Signal(this);\n this._keyBindingChanged = new Signal(this);\n }\n /**\n * A signal emitted when a command has changed.\n *\n * #### Notes\n * This signal is useful for visual representations of commands which\n * need to refresh when the state of a relevant command has changed.\n */\n get commandChanged() {\n return this._commandChanged;\n }\n /**\n * A signal emitted when a command has executed.\n *\n * #### Notes\n * Care should be taken when consuming this signal. The command system is used\n * by many components for many user actions. Handlers registered with this\n * signal must return quickly to ensure the overall application remains responsive.\n */\n get commandExecuted() {\n return this._commandExecuted;\n }\n /**\n * A signal emitted when a key binding is changed.\n */\n get keyBindingChanged() {\n return this._keyBindingChanged;\n }\n /**\n * A read-only array of the key bindings in the registry.\n */\n get keyBindings() {\n return this._keyBindings;\n }\n /**\n * List the ids of the registered commands.\n *\n * @returns A new array of the registered command ids.\n */\n listCommands() {\n return Array.from(this._commands.keys());\n }\n /**\n * Test whether a specific command is registered.\n *\n * @param id - The id of the command of interest.\n *\n * @returns `true` if the command is registered, `false` otherwise.\n */\n hasCommand(id) {\n return this._commands.has(id);\n }\n /**\n * Add a command to the registry.\n *\n * @param id - The unique id of the command.\n *\n * @param options - The options for the command.\n *\n * @returns A disposable which will remove the command.\n *\n * @throws An error if the given `id` is already registered.\n */\n addCommand(id, options) {\n // Throw an error if the id is already registered.\n if (this._commands.has(id)) {\n throw new Error(`Command '${id}' already registered.`);\n }\n // Add the command to the registry.\n this._commands.set(id, Private.createCommand(options));\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'added' });\n // Return a disposable which will remove the command.\n return new DisposableDelegate(() => {\n // Remove the command from the registry.\n this._commands.delete(id);\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'removed' });\n });\n }\n /**\n * Notify listeners that the state of a command has changed.\n *\n * @param id - The id of the command which has changed. If more than\n * one command has changed, this argument should be omitted.\n *\n * @throws An error if the given `id` is not registered.\n *\n * #### Notes\n * This method should be called by the command author whenever the\n * application state changes such that the results of the command\n * metadata functions may have changed.\n *\n * This will cause the `commandChanged` signal to be emitted.\n */\n notifyCommandChanged(id) {\n if (id !== undefined && !this._commands.has(id)) {\n throw new Error(`Command '${id}' is not registered.`);\n }\n this._commandChanged.emit({ id, type: id ? 'changed' : 'many-changed' });\n }\n /**\n * Get the description for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The description for the command.\n */\n describedBy(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return Promise.resolve((_a = cmd === null || cmd === void 0 ? void 0 : cmd.describedBy.call(undefined, args)) !== null && _a !== void 0 ? _a : { args: null });\n }\n /**\n * Get the display label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The display label for the command, or an empty string\n * if the command is not registered.\n */\n label(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return (_a = cmd === null || cmd === void 0 ? void 0 : cmd.label.call(undefined, args)) !== null && _a !== void 0 ? _a : '';\n }\n /**\n * Get the mnemonic index for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The mnemonic index for the command, or `-1` if the\n * command is not registered.\n */\n mnemonic(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.mnemonic.call(undefined, args) : -1;\n }\n /**\n * Get the icon renderer for a specific command.\n *\n * DEPRECATED: if set to a string value, the .icon field will\n * function as an alias for the .iconClass field, for backwards\n * compatibility. In the future when this is removed, the default\n * return type will become undefined.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon renderer for the command or `undefined`.\n */\n icon(id, args = JSONExt.emptyObject) {\n var _a;\n return (_a = this._commands.get(id)) === null || _a === void 0 ? void 0 : _a.icon.call(undefined, args);\n }\n /**\n * Get the icon class for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon class for the command, or an empty string if\n * the command is not registered.\n */\n iconClass(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconClass.call(undefined, args) : '';\n }\n /**\n * Get the icon label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon label for the command, or an empty string if\n * the command is not registered.\n */\n iconLabel(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconLabel.call(undefined, args) : '';\n }\n /**\n * Get the short form caption for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The caption for the command, or an empty string if the\n * command is not registered.\n */\n caption(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.caption.call(undefined, args) : '';\n }\n /**\n * Get the usage help text for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The usage text for the command, or an empty string if\n * the command is not registered.\n */\n usage(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.usage.call(undefined, args) : '';\n }\n /**\n * Get the extra class name for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The class name for the command, or an empty string if\n * the command is not registered.\n */\n className(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.className.call(undefined, args) : '';\n }\n /**\n * Get the dataset for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The dataset for the command, or an empty dataset if\n * the command is not registered.\n */\n dataset(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.dataset.call(undefined, args) : {};\n }\n /**\n * Test whether a specific command is enabled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is enabled,\n * or `false` if the command is not registered.\n */\n isEnabled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isEnabled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggled,\n * or `false` if the command is not registered.\n */\n isToggled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggleable.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggleable,\n * or `false` if the command is not registered.\n */\n isToggleable(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggleable : false;\n }\n /**\n * Test whether a specific command is visible.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is visible,\n * or `false` if the command is not registered.\n */\n isVisible(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isVisible.call(undefined, args) : false;\n }\n /**\n * Execute a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A promise which resolves with the result of the command.\n *\n * #### Notes\n * The promise will reject if the command throws an exception,\n * or if the command is not registered.\n */\n execute(id, args = JSONExt.emptyObject) {\n // Reject if the command is not registered.\n let cmd = this._commands.get(id);\n if (!cmd) {\n return Promise.reject(new Error(`Command '${id}' not registered.`));\n }\n // Execute the command and reject if an exception is thrown.\n let value;\n try {\n value = cmd.execute.call(undefined, args);\n }\n catch (err) {\n value = Promise.reject(err);\n }\n // Create the return promise which resolves the result.\n let result = Promise.resolve(value);\n // Emit the command executed signal.\n this._commandExecuted.emit({ id, args, result });\n // Return the result promise to the caller.\n return result;\n }\n /**\n * Add a key binding to the registry.\n *\n * @param options - The options for creating the key binding.\n *\n * @returns A disposable which removes the added key binding.\n *\n * #### Notes\n * If multiple key bindings are registered for the same sequence, the\n * binding with the highest selector specificity is executed first. A\n * tie is broken by using the most recently added key binding.\n *\n * Ambiguous key bindings are resolved with a timeout. As an example,\n * suppose two key bindings are registered: one with the key sequence\n * `['Ctrl D']`, and another with `['Ctrl D', 'Ctrl W']`. If the user\n * presses `Ctrl D`, the first binding cannot be immediately executed\n * since the user may intend to complete the chord with `Ctrl W`. For\n * such cases, a timer is used to allow the chord to be completed. If\n * the chord is not completed before the timeout, the first binding\n * is executed.\n */\n addKeyBinding(options) {\n // Create the binding for the given options.\n let binding = Private.createKeyBinding(options);\n // Add the key binding to the bindings array.\n this._keyBindings.push(binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'added' });\n // Return a disposable which will remove the binding.\n return new DisposableDelegate(() => {\n // Remove the binding from the array.\n ArrayExt.removeFirstOf(this._keyBindings, binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'removed' });\n });\n }\n /**\n * Process a `'keydown'` event and invoke a matching key binding.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * #### Notes\n * This should be called in response to a `'keydown'` event in order\n * to invoke the command for the best matching key binding.\n *\n * The registry **does not** install its own listener for `'keydown'`\n * events. This allows the application full control over the nodes\n * and phase for which the registry processes `'keydown'` events.\n *\n * When the keydown event is processed, if the event target or any of its\n * ancestor nodes has a `data-lm-suppress-shortcuts` attribute, its keydown\n * events will not invoke commands.\n */\n processKeydownEvent(event) {\n // Bail immediately if playing back keystrokes.\n if (this._replaying || CommandRegistry.isModifierKeyPressed(event)) {\n return;\n }\n // Get the normalized keystroke for the event.\n let keystroke = CommandRegistry.keystrokeForKeydownEvent(event);\n // If the keystroke is not valid for the keyboard layout, replay\n // any suppressed events and clear the pending state.\n if (!keystroke) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Add the keystroke to the current key sequence.\n this._keystrokes.push(keystroke);\n // Find the exact and partial matches for the key sequence.\n let { exact, partial } = Private.matchKeyBinding(this._keyBindings, this._keystrokes, event);\n // If there is no exact match and no partial match, replay\n // any suppressed events and clear the pending state.\n if (!exact && !partial) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Stop propagation of the event. If there is only a partial match,\n // the event will be replayed if a final exact match never occurs.\n event.preventDefault();\n event.stopPropagation();\n // If there is an exact match but no partial match, the exact match\n // can be dispatched immediately. The pending state is cleared so\n // the next key press starts from the default state.\n if (exact && !partial) {\n this._executeKeyBinding(exact);\n this._clearPendingState();\n return;\n }\n // If there is both an exact match and a partial match, the exact\n // match is stored for future dispatch in case the timer expires\n // before a more specific match is triggered.\n if (exact) {\n this._exactKeyMatch = exact;\n }\n // Store the event for possible playback in the future.\n this._keydownEvents.push(event);\n // (Re)start the timer to dispatch the most recent exact match\n // in case the partial match fails to result in an exact match.\n this._startTimer();\n }\n /**\n * Start or restart the pending timeout.\n */\n _startTimer() {\n this._clearTimer();\n this._timerID = window.setTimeout(() => {\n this._onPendingTimeout();\n }, Private.CHORD_TIMEOUT);\n }\n /**\n * Clear the pending timeout.\n */\n _clearTimer() {\n if (this._timerID !== 0) {\n clearTimeout(this._timerID);\n this._timerID = 0;\n }\n }\n /**\n * Replay the keydown events which were suppressed.\n */\n _replayKeydownEvents() {\n if (this._keydownEvents.length === 0) {\n return;\n }\n this._replaying = true;\n this._keydownEvents.forEach(Private.replayKeyEvent);\n this._replaying = false;\n }\n /**\n * Execute the command for the given key binding.\n *\n * If the command is missing or disabled, a warning will be logged.\n */\n _executeKeyBinding(binding) {\n let { command, args } = binding;\n let newArgs = {\n _luminoEvent: { type: 'keybinding', keys: binding.keys },\n ...args\n };\n if (!this.hasCommand(command) || !this.isEnabled(command, newArgs)) {\n let word = this.hasCommand(command) ? 'enabled' : 'registered';\n let keys = binding.keys.join(', ');\n let msg1 = `Cannot execute key binding '${keys}':`;\n let msg2 = `command '${command}' is not ${word}.`;\n console.warn(`${msg1} ${msg2}`);\n return;\n }\n this.execute(command, newArgs);\n }\n /**\n * Clear the internal pending state.\n */\n _clearPendingState() {\n this._clearTimer();\n this._exactKeyMatch = null;\n this._keystrokes.length = 0;\n this._keydownEvents.length = 0;\n }\n /**\n * Handle the partial match timeout.\n */\n _onPendingTimeout() {\n this._timerID = 0;\n if (this._exactKeyMatch) {\n this._executeKeyBinding(this._exactKeyMatch);\n }\n else {\n this._replayKeydownEvents();\n }\n this._clearPendingState();\n }\n}\n/**\n * The namespace for the `CommandRegistry` class statics.\n */\n(function (CommandRegistry) {\n /**\n * Parse a keystroke into its constituent components.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The parsed components of the keystroke.\n *\n * #### Notes\n * The keystroke should be of the form:\n * `[ [ [ ]]]`\n *\n * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and\n * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and\n * `Ctrl` on all other platforms.\n *\n * The parsing is tolerant and will not throw exceptions. Notably:\n * - Duplicate modifiers are ignored.\n * - Extra primary keys are ignored.\n * - The order of modifiers and primary key is irrelevant.\n * - The keystroke parts should be separated by whitespace.\n * - The keystroke is case sensitive.\n */\n function parseKeystroke(keystroke) {\n let key = '';\n let alt = false;\n let cmd = false;\n let ctrl = false;\n let shift = false;\n for (let token of keystroke.split(/\\s+/)) {\n if (token === 'Accel') {\n if (Platform.IS_MAC) {\n cmd = true;\n }\n else {\n ctrl = true;\n }\n }\n else if (token === 'Alt') {\n alt = true;\n }\n else if (token === 'Cmd') {\n cmd = true;\n }\n else if (token === 'Ctrl') {\n ctrl = true;\n }\n else if (token === 'Shift') {\n shift = true;\n }\n else if (token.length > 0) {\n key = token;\n }\n }\n return { cmd, ctrl, alt, shift, key };\n }\n CommandRegistry.parseKeystroke = parseKeystroke;\n /**\n * Normalize a keystroke into a canonical representation.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The normalized representation of the keystroke.\n *\n * #### Notes\n * This normalizes the keystroke by removing duplicate modifiers and\n * extra primary keys, and assembling the parts in a canonical order.\n *\n * The `Cmd` modifier is ignored on non-Mac platforms.\n */\n function normalizeKeystroke(keystroke) {\n let mods = '';\n let parts = parseKeystroke(keystroke);\n if (parts.ctrl) {\n mods += 'Ctrl ';\n }\n if (parts.alt) {\n mods += 'Alt ';\n }\n if (parts.shift) {\n mods += 'Shift ';\n }\n if (parts.cmd && Platform.IS_MAC) {\n mods += 'Cmd ';\n }\n return mods + parts.key;\n }\n CommandRegistry.normalizeKeystroke = normalizeKeystroke;\n /**\n * Get the platform-specific normalized keys for an options object.\n *\n * @param options - The options for the key binding.\n *\n * @returns Array of combined, normalized keys.\n */\n function normalizeKeys(options) {\n let keys;\n if (Platform.IS_WIN) {\n keys = options.winKeys || options.keys;\n }\n else if (Platform.IS_MAC) {\n keys = options.macKeys || options.keys;\n }\n else {\n keys = options.linuxKeys || options.keys;\n }\n return keys.map(normalizeKeystroke);\n }\n CommandRegistry.normalizeKeys = normalizeKeys;\n /**\n * Format keystrokes for display on the local system.\n *\n * If a list of keystrokes is provided, it will be displayed as\n * a comma-separated string\n *\n * @param keystroke The keystrokes to format\n * @returns The keystrokes representation\n */\n function formatKeystroke(keystroke) {\n return typeof keystroke === 'string'\n ? formatSingleKey(keystroke)\n : keystroke.map(formatSingleKey).join(', ');\n function formatSingleKey(key) {\n let mods = [];\n let separator = Platform.IS_MAC ? ' ' : '+';\n let parts = parseKeystroke(key);\n if (parts.ctrl) {\n mods.push('Ctrl');\n }\n if (parts.alt) {\n mods.push('Alt');\n }\n if (parts.shift) {\n mods.push('Shift');\n }\n if (Platform.IS_MAC && parts.cmd) {\n mods.push('Cmd');\n }\n mods.push(parts.key);\n return mods.map(Private.formatKey).join(separator);\n }\n }\n CommandRegistry.formatKeystroke = formatKeystroke;\n /**\n * Check if `'keydown'` event is caused by pressing a modifier key that should be ignored.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns `true` if modifier key was pressed, `false` otherwise.\n */\n function isModifierKeyPressed(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n return layout.isModifierKey(key);\n }\n CommandRegistry.isModifierKeyPressed = isModifierKeyPressed;\n /**\n * Create a normalized keystroke for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns A normalized keystroke, or an empty string if the event\n * does not represent a valid keystroke for the given layout.\n */\n function keystrokeForKeydownEvent(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n if (!key || layout.isModifierKey(key)) {\n return '';\n }\n let mods = [];\n if (event.ctrlKey) {\n mods.push('Ctrl');\n }\n if (event.altKey) {\n mods.push('Alt');\n }\n if (event.shiftKey) {\n mods.push('Shift');\n }\n if (event.metaKey && Platform.IS_MAC) {\n mods.push('Cmd');\n }\n mods.push(key);\n return mods.join(' ');\n }\n CommandRegistry.keystrokeForKeydownEvent = keystrokeForKeydownEvent;\n})(CommandRegistry || (CommandRegistry = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The timeout in ms for triggering a key binding chord.\n */\n Private.CHORD_TIMEOUT = 1000;\n /**\n * Create a normalized command from an options object.\n */\n function createCommand(options) {\n return {\n execute: options.execute,\n describedBy: asFunc(typeof options.describedBy === 'function'\n ? options.describedBy\n : { args: null, ...options.describedBy }, () => {\n return { args: null };\n }),\n label: asFunc(options.label, emptyStringFunc),\n mnemonic: asFunc(options.mnemonic, negativeOneFunc),\n icon: asFunc(options.icon, undefinedFunc),\n iconClass: asFunc(options.iconClass, emptyStringFunc),\n iconLabel: asFunc(options.iconLabel, emptyStringFunc),\n caption: asFunc(options.caption, emptyStringFunc),\n usage: asFunc(options.usage, emptyStringFunc),\n className: asFunc(options.className, emptyStringFunc),\n dataset: asFunc(options.dataset, emptyDatasetFunc),\n isEnabled: options.isEnabled || trueFunc,\n isToggled: options.isToggled || falseFunc,\n isToggleable: options.isToggleable || !!options.isToggled,\n isVisible: options.isVisible || trueFunc\n };\n }\n Private.createCommand = createCommand;\n /**\n * Create a key binding object from key binding options.\n */\n function createKeyBinding(options) {\n return {\n keys: CommandRegistry.normalizeKeys(options),\n selector: validateSelector(options),\n command: options.command,\n args: options.args || JSONExt.emptyObject\n };\n }\n Private.createKeyBinding = createKeyBinding;\n /**\n * Find the key bindings which match a key sequence.\n *\n * This returns a match result which contains the best exact matching\n * binding, and a flag which indicates if there are partial matches.\n */\n function matchKeyBinding(bindings, keys, event) {\n // The current best exact match.\n let exact = null;\n // Whether a partial match has been found.\n let partial = false;\n // The match distance for the exact match.\n let distance = Infinity;\n // The specificity for the exact match.\n let specificity = 0;\n // Iterate over the bindings and search for the best match.\n for (let i = 0, n = bindings.length; i < n; ++i) {\n // Lookup the current binding.\n let binding = bindings[i];\n // Check whether the key binding sequence is a match.\n let sqm = matchSequence(binding.keys, keys);\n // If there is no match, the binding is ignored.\n if (sqm === 0 /* SequenceMatch.None */) {\n continue;\n }\n // If it is a partial match and no other partial match has been\n // found, ensure the selector matches and set the partial flag.\n if (sqm === 2 /* SequenceMatch.Partial */) {\n if (!partial && targetDistance(binding.selector, event) !== -1) {\n partial = true;\n }\n continue;\n }\n // Ignore the match if the selector doesn't match, or if the\n // matched node is farther away than the current best match.\n let td = targetDistance(binding.selector, event);\n if (td === -1 || td > distance) {\n continue;\n }\n // Get the specificity for the selector.\n let sp = Selector.calculateSpecificity(binding.selector);\n // Update the best match if this match is stronger.\n if (!exact || td < distance || sp >= specificity) {\n exact = binding;\n distance = td;\n specificity = sp;\n }\n }\n // Return the match result.\n return { exact, partial };\n }\n Private.matchKeyBinding = matchKeyBinding;\n /**\n * Replay a keyboard event.\n *\n * This synthetically dispatches a clone of the keyboard event.\n */\n function replayKeyEvent(event) {\n event.target.dispatchEvent(cloneKeyboardEvent(event));\n }\n Private.replayKeyEvent = replayKeyEvent;\n function formatKey(key) {\n if (Platform.IS_MAC) {\n return MAC_DISPLAY.hasOwnProperty(key) ? MAC_DISPLAY[key] : key;\n }\n else {\n return WIN_DISPLAY.hasOwnProperty(key) ? WIN_DISPLAY[key] : key;\n }\n }\n Private.formatKey = formatKey;\n const MAC_DISPLAY = {\n Backspace: '⌫',\n Tab: '⇥',\n Enter: '⏎',\n Shift: '⇧',\n Ctrl: '⌃',\n Alt: '⌥',\n Escape: '⎋',\n PageUp: '⇞',\n PageDown: '⇟',\n End: '↘',\n Home: '↖',\n ArrowLeft: '←',\n ArrowUp: '↑',\n ArrowRight: '→',\n ArrowDown: '↓',\n Delete: '⌦',\n Cmd: '⌘'\n };\n const WIN_DISPLAY = {\n Escape: 'Esc',\n PageUp: 'Page Up',\n PageDown: 'Page Down',\n ArrowLeft: 'Left',\n ArrowUp: 'Up',\n ArrowRight: 'Right',\n ArrowDown: 'Down',\n Delete: 'Del'\n };\n /**\n * A singleton empty string function.\n */\n const emptyStringFunc = () => '';\n /**\n * A singleton `-1` number function\n */\n const negativeOneFunc = () => -1;\n /**\n * A singleton true boolean function.\n */\n const trueFunc = () => true;\n /**\n * A singleton false boolean function.\n */\n const falseFunc = () => false;\n /**\n * A singleton empty dataset function.\n */\n const emptyDatasetFunc = () => ({});\n /**\n * A singleton undefined function\n */\n const undefinedFunc = () => undefined;\n /**\n * Cast a value or command func to a command func.\n */\n function asFunc(value, dfault) {\n if (value === undefined) {\n return dfault;\n }\n if (typeof value === 'function') {\n return value;\n }\n return () => value;\n }\n /**\n * Validate the selector for an options object.\n *\n * This returns the validated selector, or throws if the selector is\n * invalid or contains commas.\n */\n function validateSelector(options) {\n if (options.selector.indexOf(',') !== -1) {\n throw new Error(`Selector cannot contain commas: ${options.selector}`);\n }\n if (!Selector.isValid(options.selector)) {\n throw new Error(`Invalid selector: ${options.selector}`);\n }\n return options.selector;\n }\n /**\n * Test whether a key binding sequence matches a key sequence.\n *\n * Returns a `SequenceMatch` value indicating the type of match.\n */\n function matchSequence(bindKeys, userKeys) {\n if (bindKeys.length < userKeys.length) {\n return 0 /* SequenceMatch.None */;\n }\n for (let i = 0, n = userKeys.length; i < n; ++i) {\n if (bindKeys[i] !== userKeys[i]) {\n return 0 /* SequenceMatch.None */;\n }\n }\n if (bindKeys.length > userKeys.length) {\n return 2 /* SequenceMatch.Partial */;\n }\n return 1 /* SequenceMatch.Exact */;\n }\n /**\n * Find the distance from the target node to the first matching node.\n *\n * This traverses the event path from `target` to `currentTarget` and\n * computes the distance from `target` to the first node which matches\n * the CSS selector. If no match is found, `-1` is returned.\n */\n function targetDistance(selector, event) {\n let targ = event.target;\n let curr = event.currentTarget;\n for (let dist = 0; targ !== null; targ = targ.parentElement, ++dist) {\n if (targ.hasAttribute('data-lm-suppress-shortcuts')) {\n return -1;\n }\n if (Selector.matches(targ, selector)) {\n return dist;\n }\n if (targ === curr) {\n return -1;\n }\n }\n return -1;\n }\n /**\n * Clone a keyboard event.\n */\n function cloneKeyboardEvent(event) {\n // A custom event is required because Chrome nulls out the\n // `keyCode` field in user-generated `KeyboardEvent` types.\n let clone = document.createEvent('Event');\n let bubbles = event.bubbles || true;\n let cancelable = event.cancelable || true;\n clone.initEvent(event.type || 'keydown', bubbles, cancelable);\n clone.key = event.key || '';\n clone.keyCode = event.keyCode || 0;\n clone.which = event.keyCode || 0;\n clone.ctrlKey = event.ctrlKey || false;\n clone.altKey = event.altKey || false;\n clone.shiftKey = event.shiftKey || false;\n clone.metaKey = event.metaKey || false;\n clone.view = event.view || window;\n return clone;\n }\n})(Private || (Private = {}));\n\nexport { CommandRegistry };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nfunction* chain(...objects) {\n for (const object of objects) {\n yield* object;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nfunction* empty() {\n return;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nfunction* enumerate(object, start = 0) {\n for (const value of object) {\n yield [start++, value];\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* filter(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nfunction find(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nfunction findIndex(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nfunction min(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nfunction max(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nfunction minmax(object, fn) {\n let empty = true;\n let vmin;\n let vmax;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n }\n else if (fn(value, vmin) < 0) {\n vmin = value;\n }\n else if (fn(value, vmax) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin, vmax];\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nfunction toArray(object) {\n return Array.from(object);\n}\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nfunction toObject(object) {\n const result = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nfunction each(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nfunction every(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nfunction some(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* map(object, fn) {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nfunction* range(start, stop, step) {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n }\n else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nfunction reduce(object, fn, initial) {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n // Setup the initial accumlated value.\n let accumulator;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n }\n else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n // Iterate the rest of the values, updating the accumulator.\n let next;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n // Return the final accumulated value.\n return accumulator;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nfunction* repeat(value, count) {\n while (0 < count--) {\n yield value;\n }\n}\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nfunction* once(value) {\n yield value;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nfunction* retro(object) {\n if (typeof object.retro === 'function') {\n yield* object.retro();\n }\n else {\n for (let index = object.length - 1; index > -1; index--) {\n yield object[index];\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nfunction* stride(object, step) {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nfunction* take(object, count) {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nfunction* zip(...objects) {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n\nexport { ArrayExt, StringExt, chain, each, empty, enumerate, every, filter, find, findIndex, map, max, min, minmax, once, range, reduce, repeat, retro, some, stride, take, toArray, toObject, topologicSort, zip };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2019, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for clipboard related functionality.\n */\nvar ClipboardExt;\n(function (ClipboardExt) {\n /**\n * Copy text to the system clipboard.\n *\n * @param text - The text to copy to the clipboard.\n */\n function copyText(text) {\n // Fetch the document body.\n const body = document.body;\n // Set up the clipboard event listener.\n const handler = (event) => {\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Set the clipboard data.\n event.clipboardData.setData('text', text);\n // Remove the event listener.\n body.removeEventListener('copy', handler, true);\n };\n // Add the event listener.\n body.addEventListener('copy', handler, true);\n // Trigger the event.\n document.execCommand('copy');\n }\n ClipboardExt.copyText = copyText;\n})(ClipboardExt || (ClipboardExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for element related utilities.\n */\nvar ElementExt;\n(function (ElementExt) {\n /**\n * Compute the box sizing for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The box sizing data for the specified element.\n */\n function boxSizing(element) {\n let style = window.getComputedStyle(element);\n let bt = parseFloat(style.borderTopWidth) || 0;\n let bl = parseFloat(style.borderLeftWidth) || 0;\n let br = parseFloat(style.borderRightWidth) || 0;\n let bb = parseFloat(style.borderBottomWidth) || 0;\n let pt = parseFloat(style.paddingTop) || 0;\n let pl = parseFloat(style.paddingLeft) || 0;\n let pr = parseFloat(style.paddingRight) || 0;\n let pb = parseFloat(style.paddingBottom) || 0;\n let hs = bl + pl + pr + br;\n let vs = bt + pt + pb + bb;\n return {\n borderTop: bt,\n borderLeft: bl,\n borderRight: br,\n borderBottom: bb,\n paddingTop: pt,\n paddingLeft: pl,\n paddingRight: pr,\n paddingBottom: pb,\n horizontalSum: hs,\n verticalSum: vs\n };\n }\n ElementExt.boxSizing = boxSizing;\n /**\n * Compute the size limits for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The size limit data for the specified element.\n */\n function sizeLimits(element) {\n let style = window.getComputedStyle(element);\n let minWidth = parseFloat(style.minWidth) || 0;\n let minHeight = parseFloat(style.minHeight) || 0;\n let maxWidth = parseFloat(style.maxWidth) || Infinity;\n let maxHeight = parseFloat(style.maxHeight) || Infinity;\n maxWidth = Math.max(minWidth, maxWidth);\n maxHeight = Math.max(minHeight, maxHeight);\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n ElementExt.sizeLimits = sizeLimits;\n /**\n * Test whether a client position lies within an element.\n *\n * @param element - The DOM element of interest.\n *\n * @param clientX - The client X coordinate of interest.\n *\n * @param clientY - The client Y coordinate of interest.\n *\n * @returns Whether the point is within the given element.\n */\n function hitTest(element, clientX, clientY) {\n let rect = element.getBoundingClientRect();\n return (clientX >= rect.left &&\n clientX < rect.right &&\n clientY >= rect.top &&\n clientY < rect.bottom);\n }\n ElementExt.hitTest = hitTest;\n /**\n * Vertically scroll an element into view if needed.\n *\n * @param area - The scroll area element.\n *\n * @param element - The element of interest.\n *\n * #### Notes\n * This follows the \"nearest\" behavior of the native `scrollIntoView`\n * method, which is not supported by all browsers.\n * https://drafts.csswg.org/cssom-view/#element-scrolling-members\n *\n * If the element fully covers the visible area or is fully contained\n * within the visible area, no scrolling will take place. Otherwise,\n * the nearest edges of the area and element are aligned.\n */\n function scrollIntoViewIfNeeded(area, element) {\n let ar = area.getBoundingClientRect();\n let er = element.getBoundingClientRect();\n if (er.top <= ar.top && er.bottom >= ar.bottom) {\n return;\n }\n if (er.top < ar.top && er.height <= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.bottom > ar.bottom && er.height >= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.top < ar.top && er.height > ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n if (er.bottom > ar.bottom && er.height < ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n }\n ElementExt.scrollIntoViewIfNeeded = scrollIntoViewIfNeeded;\n})(ElementExt || (ElementExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for platform related utilities.\n */\nvar Platform;\n(function (Platform) {\n /**\n * A flag indicating whether the platform is Mac.\n */\n Platform.IS_MAC = !!navigator.platform.match(/Mac/i);\n /**\n * A flag indicating whether the platform is Windows.\n */\n Platform.IS_WIN = !!navigator.platform.match(/Win/i);\n /**\n * A flag indicating whether the browser is IE.\n */\n Platform.IS_IE = /Trident/.test(navigator.userAgent);\n /**\n * A flag indicating whether the browser is Edge.\n */\n Platform.IS_EDGE = /Edge/.test(navigator.userAgent);\n /**\n * Test whether the `accel` key is pressed.\n *\n * @param event - The keyboard or mouse event of interest.\n *\n * @returns Whether the `accel` key is pressed.\n *\n * #### Notes\n * On Mac the `accel` key is the command key. On all other\n * platforms the `accel` key is the control key.\n */\n function accelKey(event) {\n return Platform.IS_MAC ? event.metaKey : event.ctrlKey;\n }\n Platform.accelKey = accelKey;\n})(Platform || (Platform = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for selector related utilities.\n */\nvar Selector;\n(function (Selector) {\n /**\n * Calculate the specificity of a single CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns The specificity of the selector.\n *\n * #### Undefined Behavior\n * The selector is invalid.\n *\n * #### Notes\n * This is based on https://www.w3.org/TR/css3-selectors/#specificity\n *\n * A larger number represents a more specific selector.\n *\n * The smallest possible specificity is `0`.\n *\n * The result is represented as a hex number `0x` where\n * each component is the count of the respective selector clause.\n *\n * If the selector contains commas, only the first clause is used.\n *\n * The computed result is cached, so subsequent calculations for the\n * same selector are extremely fast.\n */\n function calculateSpecificity(selector) {\n if (selector in Private.specificityCache) {\n return Private.specificityCache[selector];\n }\n let result = Private.calculateSingle(selector);\n return (Private.specificityCache[selector] = result);\n }\n Selector.calculateSpecificity = calculateSpecificity;\n /**\n * Test whether a selector is a valid CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns `true` if the selector is valid, `false` otherwise.\n *\n * #### Notes\n * The computed result is cached, so subsequent tests for the same\n * selector are extremely fast.\n */\n function isValid(selector) {\n if (selector in Private.validityCache) {\n return Private.validityCache[selector];\n }\n let result = true;\n try {\n Private.testElem.querySelector(selector);\n }\n catch (err) {\n result = false;\n }\n return (Private.validityCache[selector] = result);\n }\n Selector.isValid = isValid;\n /**\n * Test whether an element matches a CSS selector.\n *\n * @param element - The element of interest.\n *\n * @param selector - The valid CSS selector of interest.\n *\n * @returns `true` if the element is a match, `false` otherwise.\n *\n * #### Notes\n * This function uses the builtin browser capabilities when possible,\n * falling back onto a document query otherwise.\n */\n function matches(element, selector) {\n return Private.protoMatchFunc.call(element, selector);\n }\n Selector.matches = matches;\n})(Selector || (Selector = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A cache of computed selector specificity values.\n */\n Private.specificityCache = Object.create(null);\n /**\n * A cache of computed selector validity.\n */\n Private.validityCache = Object.create(null);\n /**\n * An empty element for testing selector validity.\n */\n Private.testElem = document.createElement('div');\n /**\n * A cross-browser CSS selector matching prototype function.\n */\n Private.protoMatchFunc = (() => {\n let proto = Element.prototype;\n return (proto.matches ||\n proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector ||\n function (selector) {\n let elem = this;\n let matches = elem.ownerDocument\n ? elem.ownerDocument.querySelectorAll(selector)\n : [];\n return Array.prototype.indexOf.call(matches, elem) !== -1;\n });\n })();\n /**\n * Calculate the specificity of a single selector.\n *\n * The behavior is undefined if the selector is invalid.\n */\n function calculateSingle(selector) {\n // Ignore anything after the first comma.\n selector = selector.split(',', 1)[0];\n // Setup the aggregate counters.\n let a = 0;\n let b = 0;\n let c = 0;\n // Apply a regex to the front of the selector. If it succeeds, that\n // portion of the selector is removed. Returns a success/fail flag.\n function match(re) {\n let match = selector.match(re);\n if (match === null) {\n return false;\n }\n selector = selector.slice(match[0].length);\n return true;\n }\n // Replace the negation pseudo-class (which is ignored),\n // but keep its inner content (which is not ignored).\n selector = selector.replace(NEGATION_RE, ' $1 ');\n // Continue matching until the selector is consumed.\n while (selector.length > 0) {\n // Match an ID selector.\n if (match(ID_RE)) {\n a++;\n continue;\n }\n // Match a class selector.\n if (match(CLASS_RE)) {\n b++;\n continue;\n }\n // Match an attribute selector.\n if (match(ATTR_RE)) {\n b++;\n continue;\n }\n // Match a pseudo-element selector. This is done before matching\n // a pseudo-class since this regex overlaps with that regex.\n if (match(PSEUDO_ELEM_RE)) {\n c++;\n continue;\n }\n // Match a pseudo-class selector.\n if (match(PSEDUO_CLASS_RE)) {\n b++;\n continue;\n }\n // Match a plain type selector.\n if (match(TYPE_RE)) {\n c++;\n continue;\n }\n // Finally, match any ignored characters.\n if (match(IGNORE_RE)) {\n continue;\n }\n // At this point, the selector is assumed to be invalid.\n return 0;\n }\n // Clamp each component to a reasonable base.\n a = Math.min(a, 0xff);\n b = Math.min(b, 0xff);\n c = Math.min(c, 0xff);\n // Combine the components into a single result.\n return (a << 16) | (b << 8) | c;\n }\n Private.calculateSingle = calculateSingle;\n /**\n * A regex which matches an ID selector at string start.\n */\n const ID_RE = /^#[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a class selector at string start.\n */\n const CLASS_RE = /^\\.[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches an attribute selector at string start.\n */\n const ATTR_RE = /^\\[[^\\]]+\\]/;\n /**\n * A regex which matches a type selector at string start.\n */\n const TYPE_RE = /^[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a pseudo-element selector at string start.\n */\n const PSEUDO_ELEM_RE = /^(::[^\\s\\+>~#\\.\\[:]+|:first-line|:first-letter|:before|:after)/;\n /**\n * A regex which matches a pseudo-class selector at string start.\n */\n const PSEDUO_CLASS_RE = /^:[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches ignored characters at string start.\n */\n const IGNORE_RE = /^[\\s\\+>~\\*]+/;\n /**\n * A regex which matches the negation pseudo-class globally.\n */\n const NEGATION_RE = /:not\\(([^\\)]+)\\)/g;\n})(Private || (Private = {}));\n\nexport { ClipboardExt, ElementExt, Platform, Selector };\n//# sourceMappingURL=index.es6.js.map\n","/**\n * A generic doubly-linked list.\n */\nclass LinkedList {\n constructor() {\n this._first = null;\n this._last = null;\n this._size = 0;\n }\n /**\n * Whether the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get isEmpty() {\n return this._size === 0;\n }\n /**\n * The size of the list.\n *\n * #### Complexity\n * `O(1)`\n *\n * #### Notes\n * This is equivalent to `length`.\n */\n get size() {\n return this._size;\n }\n /**\n * The length of the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `size`.\n *\n * This property is deprecated.\n */\n get length() {\n return this._size;\n }\n /**\n * The first value in the list.\n *\n * This is `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get first() {\n return this._first ? this._first.value : undefined;\n }\n /**\n * The last value in the list.\n *\n * This is `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get last() {\n return this._last ? this._last.value : undefined;\n }\n /**\n * The first node in the list.\n *\n * This is `null` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get firstNode() {\n return this._first;\n }\n /**\n * The last node in the list.\n *\n * This is `null` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get lastNode() {\n return this._last;\n }\n /**\n * Create an iterator over the values in the list.\n *\n * @returns A new iterator starting with the first value.\n *\n * #### Complexity\n * Constant.\n */\n *[Symbol.iterator]() {\n let node = this._first;\n while (node) {\n yield node.value;\n node = node.next;\n }\n }\n /**\n * Create a reverse iterator over the values in the list.\n *\n * @returns A new iterator starting with the last value.\n *\n * #### Complexity\n * Constant.\n */\n *retro() {\n let node = this._last;\n while (node) {\n yield node.value;\n node = node.prev;\n }\n }\n /**\n * Create an iterator over the nodes in the list.\n *\n * @returns A new iterator starting with the first node.\n *\n * #### Complexity\n * Constant.\n */\n *nodes() {\n let node = this._first;\n while (node) {\n yield node;\n node = node.next;\n }\n }\n /**\n * Create a reverse iterator over the nodes in the list.\n *\n * @returns A new iterator starting with the last node.\n *\n * #### Complexity\n * Constant.\n */\n *retroNodes() {\n let node = this._last;\n while (node) {\n yield node;\n node = node.prev;\n }\n }\n /**\n * Assign new values to the list, replacing all current values.\n *\n * @param values - The values to assign to the list.\n *\n * #### Complexity\n * Linear.\n */\n assign(values) {\n this.clear();\n for (const value of values) {\n this.addLast(value);\n }\n }\n /**\n * Add a value to the end of the list.\n *\n * @param value - The value to add to the end of the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `addLast`.\n */\n push(value) {\n this.addLast(value);\n }\n /**\n * Remove and return the value at the end of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `removeLast`.\n */\n pop() {\n return this.removeLast();\n }\n /**\n * Add a value to the beginning of the list.\n *\n * @param value - The value to add to the beginning of the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `addFirst`.\n */\n shift(value) {\n this.addFirst(value);\n }\n /**\n * Remove and return the value at the beginning of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `removeFirst`.\n */\n unshift() {\n return this.removeFirst();\n }\n /**\n * Add a value to the beginning of the list.\n *\n * @param value - The value to add to the beginning of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Complexity\n * Constant.\n */\n addFirst(value) {\n let node = new Private.LinkedListNode(this, value);\n if (!this._first) {\n this._first = node;\n this._last = node;\n }\n else {\n node.next = this._first;\n this._first.prev = node;\n this._first = node;\n }\n this._size++;\n return node;\n }\n /**\n * Add a value to the end of the list.\n *\n * @param value - The value to add to the end of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Complexity\n * Constant.\n */\n addLast(value) {\n let node = new Private.LinkedListNode(this, value);\n if (!this._last) {\n this._first = node;\n this._last = node;\n }\n else {\n node.prev = this._last;\n this._last.next = node;\n this._last = node;\n }\n this._size++;\n return node;\n }\n /**\n * Insert a value before a specific node in the list.\n *\n * @param value - The value to insert before the reference node.\n *\n * @param ref - The reference node of interest. If this is `null`,\n * the value will be added to the beginning of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Notes\n * The reference node must be owned by the list.\n *\n * #### Complexity\n * Constant.\n */\n insertBefore(value, ref) {\n if (!ref || ref === this._first) {\n return this.addFirst(value);\n }\n if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {\n throw new Error('Reference node is not owned by the list.');\n }\n let node = new Private.LinkedListNode(this, value);\n let _ref = ref;\n let prev = _ref.prev;\n node.next = _ref;\n node.prev = prev;\n _ref.prev = node;\n prev.next = node;\n this._size++;\n return node;\n }\n /**\n * Insert a value after a specific node in the list.\n *\n * @param value - The value to insert after the reference node.\n *\n * @param ref - The reference node of interest. If this is `null`,\n * the value will be added to the end of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Notes\n * The reference node must be owned by the list.\n *\n * #### Complexity\n * Constant.\n */\n insertAfter(value, ref) {\n if (!ref || ref === this._last) {\n return this.addLast(value);\n }\n if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {\n throw new Error('Reference node is not owned by the list.');\n }\n let node = new Private.LinkedListNode(this, value);\n let _ref = ref;\n let next = _ref.next;\n node.next = next;\n node.prev = _ref;\n _ref.next = node;\n next.prev = node;\n this._size++;\n return node;\n }\n /**\n * Remove and return the value at the beginning of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n removeFirst() {\n let node = this._first;\n if (!node) {\n return undefined;\n }\n if (node === this._last) {\n this._first = null;\n this._last = null;\n }\n else {\n this._first = node.next;\n this._first.prev = null;\n }\n node.list = null;\n node.next = null;\n node.prev = null;\n this._size--;\n return node.value;\n }\n /**\n * Remove and return the value at the end of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n removeLast() {\n let node = this._last;\n if (!node) {\n return undefined;\n }\n if (node === this._first) {\n this._first = null;\n this._last = null;\n }\n else {\n this._last = node.prev;\n this._last.next = null;\n }\n node.list = null;\n node.next = null;\n node.prev = null;\n this._size--;\n return node.value;\n }\n /**\n * Remove a specific node from the list.\n *\n * @param node - The node to remove from the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * The node must be owned by the list.\n */\n removeNode(node) {\n if (!(node instanceof Private.LinkedListNode) || node.list !== this) {\n throw new Error('Node is not owned by the list.');\n }\n let _node = node;\n if (_node === this._first && _node === this._last) {\n this._first = null;\n this._last = null;\n }\n else if (_node === this._first) {\n this._first = _node.next;\n this._first.prev = null;\n }\n else if (_node === this._last) {\n this._last = _node.prev;\n this._last.next = null;\n }\n else {\n _node.next.prev = _node.prev;\n _node.prev.next = _node.next;\n }\n _node.list = null;\n _node.next = null;\n _node.prev = null;\n this._size--;\n }\n /**\n * Remove all values from the list.\n *\n * #### Complexity\n * Linear.\n */\n clear() {\n let node = this._first;\n while (node) {\n let next = node.next;\n node.list = null;\n node.prev = null;\n node.next = null;\n node = next;\n }\n this._first = null;\n this._last = null;\n this._size = 0;\n }\n}\n/**\n * The namespace for the `LinkedList` class statics.\n */\n(function (LinkedList) {\n /**\n * Create a linked list from an iterable of values.\n *\n * @param values - The iterable object of interest.\n *\n * @returns A new linked list initialized with the given values.\n *\n * #### Complexity\n * Linear.\n */\n function from(values) {\n let list = new LinkedList();\n list.assign(values);\n return list;\n }\n LinkedList.from = from;\n})(LinkedList || (LinkedList = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The internal linked list node implementation.\n */\n class LinkedListNode {\n /**\n * Construct a new linked list node.\n *\n * @param list - The list which owns the node.\n *\n * @param value - The value for the link.\n */\n constructor(list, value) {\n /**\n * The linked list which created and owns the node.\n */\n this.list = null;\n /**\n * The next node in the list.\n */\n this.next = null;\n /**\n * The previous node in the list.\n */\n this.prev = null;\n this.list = list;\n this.value = value;\n }\n }\n Private.LinkedListNode = LinkedListNode;\n})(Private || (Private = {}));\n\nexport { LinkedList };\n//# sourceMappingURL=index.es6.js.map\n","import { every, retro, some, ArrayExt } from '@lumino/algorithm';\nimport { LinkedList } from '@lumino/collections';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module messaging\n */\n/**\n * A message which can be delivered to a message handler.\n *\n * #### Notes\n * This class may be subclassed to create complex message types.\n */\nclass Message {\n /**\n * Construct a new message.\n *\n * @param type - The type of the message.\n */\n constructor(type) {\n this.type = type;\n }\n /**\n * Test whether the message is conflatable.\n *\n * #### Notes\n * Message conflation is an advanced topic. Most message types will\n * not make use of this feature.\n *\n * If a conflatable message is posted to a handler while another\n * conflatable message of the same `type` has already been posted\n * to the handler, the `conflate()` method of the existing message\n * will be invoked. If that method returns `true`, the new message\n * will not be enqueued. This allows messages to be compressed, so\n * that only a single instance of the message type is processed per\n * cycle, no matter how many times messages of that type are posted.\n *\n * Custom message types may reimplement this property.\n *\n * The default implementation is always `false`.\n */\n get isConflatable() {\n return false;\n }\n /**\n * Conflate this message with another message of the same `type`.\n *\n * @param other - A conflatable message of the same `type`.\n *\n * @returns `true` if the message was successfully conflated, or\n * `false` otherwise.\n *\n * #### Notes\n * Message conflation is an advanced topic. Most message types will\n * not make use of this feature.\n *\n * This method is called automatically by the message loop when the\n * given message is posted to the handler paired with this message.\n * This message will already be enqueued and conflatable, and the\n * given message will have the same `type` and also be conflatable.\n *\n * This method should merge the state of the other message into this\n * message as needed so that when this message is finally delivered\n * to the handler, it receives the most up-to-date information.\n *\n * If this method returns `true`, it signals that the other message\n * was successfully conflated and that message will not be enqueued.\n *\n * If this method returns `false`, the other message will be enqueued\n * for normal delivery.\n *\n * Custom message types may reimplement this method.\n *\n * The default implementation always returns `false`.\n */\n conflate(other) {\n return false;\n }\n}\n/**\n * A convenience message class which conflates automatically.\n *\n * #### Notes\n * Message conflation is an advanced topic. Most user code will not\n * make use of this class.\n *\n * This message class is useful for creating message instances which\n * should be conflated, but which have no state other than `type`.\n *\n * If conflation of stateful messages is required, a custom `Message`\n * subclass should be created.\n */\nclass ConflatableMessage extends Message {\n /**\n * Test whether the message is conflatable.\n *\n * #### Notes\n * This property is always `true`.\n */\n get isConflatable() {\n return true;\n }\n /**\n * Conflate this message with another message of the same `type`.\n *\n * #### Notes\n * This method always returns `true`.\n */\n conflate(other) {\n return true;\n }\n}\n/**\n * The namespace for the global singleton message loop.\n */\nvar MessageLoop;\n(function (MessageLoop) {\n /**\n * A function that cancels the pending loop task; `null` if unavailable.\n */\n let pending = null;\n /**\n * Schedules a function for invocation as soon as possible asynchronously.\n *\n * @param fn The function to invoke when called back.\n *\n * @returns An anonymous function that will unschedule invocation if possible.\n */\n const schedule = (resolved => (fn) => {\n let rejected = false;\n resolved.then(() => !rejected && fn());\n return () => {\n rejected = true;\n };\n })(Promise.resolve());\n /**\n * Send a message to a message handler to process immediately.\n *\n * @param handler - The handler which should process the message.\n *\n * @param msg - The message to deliver to the handler.\n *\n * #### Notes\n * The message will first be sent through any installed message hooks\n * for the handler. If the message passes all hooks, it will then be\n * delivered to the `processMessage` method of the handler.\n *\n * The message will not be conflated with pending posted messages.\n *\n * Exceptions in hooks and handlers will be caught and logged.\n */\n function sendMessage(handler, msg) {\n // Lookup the message hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Handle the common case of no installed hooks.\n if (!hooks || hooks.length === 0) {\n invokeHandler(handler, msg);\n return;\n }\n // Invoke the message hooks starting with the newest first.\n let passed = every(retro(hooks), hook => {\n return hook ? invokeHook(hook, handler, msg) : true;\n });\n // Invoke the handler if the message passes all hooks.\n if (passed) {\n invokeHandler(handler, msg);\n }\n }\n MessageLoop.sendMessage = sendMessage;\n /**\n * Post a message to a message handler to process in the future.\n *\n * @param handler - The handler which should process the message.\n *\n * @param msg - The message to post to the handler.\n *\n * #### Notes\n * The message will be conflated with the pending posted messages for\n * the handler, if possible. If the message is not conflated, it will\n * be queued for normal delivery on the next cycle of the event loop.\n *\n * Exceptions in hooks and handlers will be caught and logged.\n */\n function postMessage(handler, msg) {\n // Handle the common case of a non-conflatable message.\n if (!msg.isConflatable) {\n enqueueMessage(handler, msg);\n return;\n }\n // Conflate the message with an existing message if possible.\n let conflated = some(messageQueue, posted => {\n if (posted.handler !== handler) {\n return false;\n }\n if (!posted.msg) {\n return false;\n }\n if (posted.msg.type !== msg.type) {\n return false;\n }\n if (!posted.msg.isConflatable) {\n return false;\n }\n return posted.msg.conflate(msg);\n });\n // Enqueue the message if it was not conflated.\n if (!conflated) {\n enqueueMessage(handler, msg);\n }\n }\n MessageLoop.postMessage = postMessage;\n /**\n * Install a message hook for a message handler.\n *\n * @param handler - The message handler of interest.\n *\n * @param hook - The message hook to install.\n *\n * #### Notes\n * A message hook is invoked before a message is delivered to the\n * handler. If the hook returns `false`, no other hooks will be\n * invoked and the message will not be delivered to the handler.\n *\n * The most recently installed message hook is executed first.\n *\n * If the hook is already installed, this is a no-op.\n */\n function installMessageHook(handler, hook) {\n // Look up the hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Bail early if the hook is already installed.\n if (hooks && hooks.indexOf(hook) !== -1) {\n return;\n }\n // Add the hook to the end, so it will be the first to execute.\n if (!hooks) {\n messageHooks.set(handler, [hook]);\n }\n else {\n hooks.push(hook);\n }\n }\n MessageLoop.installMessageHook = installMessageHook;\n /**\n * Remove an installed message hook for a message handler.\n *\n * @param handler - The message handler of interest.\n *\n * @param hook - The message hook to remove.\n *\n * #### Notes\n * It is safe to call this function while the hook is executing.\n *\n * If the hook is not installed, this is a no-op.\n */\n function removeMessageHook(handler, hook) {\n // Lookup the hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Bail early if the hooks do not exist.\n if (!hooks) {\n return;\n }\n // Lookup the index of the hook and bail if not found.\n let i = hooks.indexOf(hook);\n if (i === -1) {\n return;\n }\n // Clear the hook and schedule a cleanup of the array.\n hooks[i] = null;\n scheduleCleanup(hooks);\n }\n MessageLoop.removeMessageHook = removeMessageHook;\n /**\n * Clear all message data associated with a message handler.\n *\n * @param handler - The message handler of interest.\n *\n * #### Notes\n * This will clear all posted messages and hooks for the handler.\n */\n function clearData(handler) {\n // Lookup the hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Clear all messsage hooks for the handler.\n if (hooks && hooks.length > 0) {\n ArrayExt.fill(hooks, null);\n scheduleCleanup(hooks);\n }\n // Clear all posted messages for the handler.\n for (const posted of messageQueue) {\n if (posted.handler === handler) {\n posted.handler = null;\n posted.msg = null;\n }\n }\n }\n MessageLoop.clearData = clearData;\n /**\n * Process the pending posted messages in the queue immediately.\n *\n * #### Notes\n * This function is useful when posted messages must be processed immediately.\n *\n * This function should normally not be needed, but it may be\n * required to work around certain browser idiosyncrasies.\n *\n * Recursing into this function is a no-op.\n */\n function flush() {\n // Bail if recursion is detected or if there is no pending task.\n if (flushGuard || pending === null) {\n return;\n }\n // Unschedule the pending loop task.\n pending();\n pending = null;\n // Run the message loop within the recursion guard.\n flushGuard = true;\n runMessageLoop();\n flushGuard = false;\n }\n MessageLoop.flush = flush;\n /**\n * Get the message loop exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return exceptionHandler;\n }\n MessageLoop.getExceptionHandler = getExceptionHandler;\n /**\n * Set the message loop exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a message handler or a\n * message hook throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = exceptionHandler;\n exceptionHandler = handler;\n return old;\n }\n MessageLoop.setExceptionHandler = setExceptionHandler;\n /**\n * The queue of posted message pairs.\n */\n const messageQueue = new LinkedList();\n /**\n * A mapping of handler to array of installed message hooks.\n */\n const messageHooks = new WeakMap();\n /**\n * A set of message hook arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * The message loop exception handler.\n */\n let exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * A guard flag to prevent flush recursion.\n */\n let flushGuard = false;\n /**\n * Invoke a message hook with the specified handler and message.\n *\n * Returns the result of the hook, or `true` if the hook throws.\n *\n * Exceptions in the hook will be caught and logged.\n */\n function invokeHook(hook, handler, msg) {\n let result = true;\n try {\n if (typeof hook === 'function') {\n result = hook(handler, msg);\n }\n else {\n result = hook.messageHook(handler, msg);\n }\n }\n catch (err) {\n exceptionHandler(err);\n }\n return result;\n }\n /**\n * Invoke a message handler with the specified message.\n *\n * Exceptions in the handler will be caught and logged.\n */\n function invokeHandler(handler, msg) {\n try {\n handler.processMessage(msg);\n }\n catch (err) {\n exceptionHandler(err);\n }\n }\n /**\n * Add a message to the end of the message queue.\n *\n * This will automatically schedule a run of the message loop.\n */\n function enqueueMessage(handler, msg) {\n // Add the posted message to the queue.\n messageQueue.addLast({ handler, msg });\n // Bail if a loop task is already pending.\n if (pending !== null) {\n return;\n }\n // Schedule a run of the message loop.\n pending = schedule(runMessageLoop);\n }\n /**\n * Run an iteration of the message loop.\n *\n * This will process all pending messages in the queue. If a message\n * is added to the queue while the message loop is running, it will\n * be processed on the next cycle of the loop.\n */\n function runMessageLoop() {\n // Clear the task so the next loop can be scheduled.\n pending = null;\n // If the message queue is empty, there is nothing else to do.\n if (messageQueue.isEmpty) {\n return;\n }\n // Add a sentinel value to the end of the queue. The queue will\n // only be processed up to the sentinel. Messages posted during\n // this cycle will execute on the next cycle.\n let sentinel = { handler: null, msg: null };\n messageQueue.addLast(sentinel);\n // Enter the message loop.\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // Remove the first posted message in the queue.\n let posted = messageQueue.removeFirst();\n // If the value is the sentinel, exit the loop.\n if (posted === sentinel) {\n return;\n }\n // Dispatch the message if it has not been cleared.\n if (posted.handler && posted.msg) {\n sendMessage(posted.handler, posted.msg);\n }\n }\n }\n /**\n * Schedule a cleanup of a message hooks array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any `null` hook will\n * be removed from the array.\n */\n function scheduleCleanup(hooks) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(hooks);\n }\n /**\n * Cleanup the message hook arrays in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupHooks);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty hooks in a message hooks array.\n *\n * This will remove any `null` hook from the array.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupHooks(hooks) {\n ArrayExt.removeAllWhere(hooks, isNull);\n }\n /**\n * Test whether a value is `null`.\n */\n function isNull(value) {\n return value === null;\n }\n})(MessageLoop || (MessageLoop = {}));\n\nexport { ConflatableMessage, Message, MessageLoop };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module properties\n */\n/**\n * A class which attaches a value to an external object.\n *\n * #### Notes\n * Attached properties are used to extend the state of an object with\n * semantic data from an unrelated class. They also encapsulate value\n * creation, coercion, and notification.\n *\n * Because attached property values are stored in a hash table, which\n * in turn is stored in a WeakMap keyed on the owner object, there is\n * non-trivial storage overhead involved in their use. The pattern is\n * therefore best used for the storage of rare data.\n */\nclass AttachedProperty {\n /**\n * Construct a new attached property.\n *\n * @param options - The options for initializing the property.\n */\n constructor(options) {\n this._pid = Private.nextPID();\n this.name = options.name;\n this._create = options.create;\n this._coerce = options.coerce || null;\n this._compare = options.compare || null;\n this._changed = options.changed || null;\n }\n /**\n * Get the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @returns The current value of the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and assigned as the current value of the property.\n */\n get(owner) {\n let value;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n value = map[this._pid];\n }\n else {\n value = map[this._pid] = this._createValue(owner);\n }\n return value;\n }\n /**\n * Set the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @param value - The value for the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n set(owner, value) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, value);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Explicitly coerce the current property value for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n coerce(owner) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, oldValue);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Get or create the default value for the given owner.\n */\n _createValue(owner) {\n let create = this._create;\n return create(owner);\n }\n /**\n * Coerce the value for the given owner.\n */\n _coerceValue(owner, value) {\n let coerce = this._coerce;\n return coerce ? coerce(owner, value) : value;\n }\n /**\n * Compare the old value and new value for equality.\n */\n _compareValue(oldValue, newValue) {\n let compare = this._compare;\n return compare ? compare(oldValue, newValue) : oldValue === newValue;\n }\n /**\n * Run the change notification if the given values are different.\n */\n _maybeNotify(owner, oldValue, newValue) {\n let changed = this._changed;\n if (changed && !this._compareValue(oldValue, newValue)) {\n changed(owner, oldValue, newValue);\n }\n }\n}\n/**\n * The namespace for the `AttachedProperty` class statics.\n */\n(function (AttachedProperty) {\n /**\n * Clear the stored property data for the given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * This will clear all property values for the owner, but it will\n * **not** run the change notification for any of the properties.\n */\n function clearData(owner) {\n Private.ownerData.delete(owner);\n }\n AttachedProperty.clearData = clearData;\n})(AttachedProperty || (AttachedProperty = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A weak mapping of property owner to property map.\n */\n Private.ownerData = new WeakMap();\n /**\n * A function which computes successive unique property ids.\n */\n Private.nextPID = (() => {\n let id = 0;\n return () => {\n let rand = Math.random();\n let stem = `${rand}`.slice(2);\n return `pid-${stem}-${id++}`;\n };\n })();\n /**\n * Lookup the data map for the property owner.\n *\n * This will create the map if one does not already exist.\n */\n function ensureMap(owner) {\n let map = Private.ownerData.get(owner);\n if (map) {\n return map;\n }\n map = Object.create(null);\n Private.ownerData.set(owner, map);\n return map;\n }\n Private.ensureMap = ensureMap;\n})(Private || (Private = {}));\n\nexport { AttachedProperty };\n//# sourceMappingURL=index.es6.js.map\n","import { find, ArrayExt } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nclass Signal {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender) {\n this.sender = sender;\n }\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot, thisArg) {\n return Private.connect(this, slot, thisArg);\n }\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot, thisArg) {\n return Private.disconnect(this, slot, thisArg);\n }\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args) {\n Private.emit(this, args);\n }\n}\n/**\n * The namespace for the `Signal` class statics.\n */\n(function (Signal) {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectBetween(sender, receiver) {\n Private.disconnectBetween(sender, receiver);\n }\n Signal.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n Private.disconnectSender(sender);\n }\n Signal.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectReceiver(receiver) {\n Private.disconnectReceiver(receiver);\n }\n Signal.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectAll(object) {\n Private.disconnectAll(object);\n }\n Signal.disconnectAll = disconnectAll;\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n function clearData(object) {\n Private.disconnectAll(object);\n }\n Signal.clearData = clearData;\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return Private.exceptionHandler;\n }\n Signal.getExceptionHandler = getExceptionHandler;\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n Signal.setExceptionHandler = setExceptionHandler;\n})(Signal || (Signal = {}));\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nclass Stream extends Signal {\n constructor() {\n super(...arguments);\n this._pending = new PromiseDelegate();\n }\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator]() {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n }\n catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args) {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n /**\n * Stop the stream's async iteration.\n */\n stop() {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The signal exception handler function.\n */\n Private.exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n function connect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n // Indicate a successful connection.\n return true;\n }\n Private.connect = connect;\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n function disconnect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver);\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n // Indicate a successful disconnection.\n return true;\n }\n Private.disconnect = disconnect;\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectBetween(sender, receiver) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n Private.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver));\n }\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n Private.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectReceiver(receiver) {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender));\n }\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n Private.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n function disconnectAll(object) {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n Private.disconnectAll = disconnectAll;\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n function emit(signal, args) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n Private.emit = emit;\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap();\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap();\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(connections, signal, slot, thisArg) {\n return find(connections, connection => connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg);\n }\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection, args) {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal.sender, args);\n }\n catch (err) {\n Private.exceptionHandler(err);\n }\n }\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection) {\n return connection.signal === null;\n }\n})(Private || (Private = {}));\n\nexport { Signal, Stream };\n//# sourceMappingURL=index.es6.js.map\n","import { DisposableDelegate } from '@lumino/disposable';\n\n/**\n * An object which manages a drag-drop operation.\n *\n * A drag object dispatches four different events to drop targets:\n *\n * - `'lm-dragenter'` - Dispatched when the mouse enters the target\n * element. This event must be canceled in order to receive any\n * of the other events.\n *\n * - `'lm-dragover'` - Dispatched when the mouse moves over the drop\n * target. It must cancel the event and set the `dropAction` to one\n * of the supported actions in order to receive drop events.\n *\n * - `'lm-dragleave'` - Dispatched when the mouse leaves the target\n * element. This includes moving the mouse into child elements.\n *\n * - `'lm-drop'`- Dispatched when the mouse is released over the target\n * element when the target indicates an appropriate drop action. If\n * the event is canceled, the indicated drop action is returned to\n * the initiator through the resolved promise.\n *\n * A drag operation can be terminated at any time by pressing `Escape`\n * or by disposing the drag object.\n *\n * A drag object has the ability to automatically scroll a scrollable\n * element when the mouse is hovered near one of its edges. To enable\n * this, add the `data-lm-dragscroll` attribute to any element which\n * the drag object should consider for scrolling.\n *\n * #### Notes\n * This class is designed to be used when dragging and dropping custom\n * data *within* a single application. It is *not* a replacement for\n * the native drag-drop API. Instead, it provides an API which allows\n * drag operations to be initiated programmatically and enables the\n * transfer of arbitrary non-string objects; features which are not\n * possible with the native drag-drop API.\n */\nclass Drag {\n /**\n * Construct a new drag object.\n *\n * @param options - The options for initializing the drag.\n */\n constructor(options) {\n /**\n * The scroll loop handler function.\n */\n this._onScrollFrame = () => {\n // Bail early if there is no scroll target.\n if (!this._scrollTarget) {\n return;\n }\n // Unpack the scroll target.\n let { element, edge, distance } = this._scrollTarget;\n // Calculate the scroll delta using nonlinear acceleration.\n let d = Private.SCROLL_EDGE_SIZE - distance;\n let f = Math.pow(d / Private.SCROLL_EDGE_SIZE, 2);\n let s = Math.max(1, Math.round(f * Private.SCROLL_EDGE_SIZE));\n // Scroll the element in the specified direction.\n switch (edge) {\n case 'top':\n element.scrollTop -= s;\n break;\n case 'left':\n element.scrollLeft -= s;\n break;\n case 'right':\n element.scrollLeft += s;\n break;\n case 'bottom':\n element.scrollTop += s;\n break;\n }\n // Request the next cycle of the scroll loop.\n requestAnimationFrame(this._onScrollFrame);\n };\n this._disposed = false;\n this._dropAction = 'none';\n this._override = null;\n this._currentTarget = null;\n this._currentElement = null;\n this._promise = null;\n this._scrollTarget = null;\n this._resolve = null;\n this.document = options.document || document;\n this.mimeData = options.mimeData;\n this.dragImage = options.dragImage || null;\n this.proposedAction = options.proposedAction || 'copy';\n this.supportedActions = options.supportedActions || 'all';\n this.source = options.source || null;\n }\n /**\n * Dispose of the resources held by the drag object.\n *\n * #### Notes\n * This will cancel the drag operation if it is active.\n */\n dispose() {\n // Do nothing if the drag object is already disposed.\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n // If there is a current target, dispatch a drag leave event.\n if (this._currentTarget) {\n let event = new PointerEvent('pointerup', {\n bubbles: true,\n cancelable: true,\n clientX: -1,\n clientY: -1\n });\n Private.dispatchDragLeave(this, this._currentTarget, null, event);\n }\n // Finalize the drag object with `'none'`.\n this._finalize('none');\n }\n /**\n * Test whether the drag object is disposed.\n */\n get isDisposed() {\n return this._disposed;\n }\n /**\n * Start the drag operation at the specified client position.\n *\n * @param clientX - The client X position for the drag start.\n *\n * @param clientY - The client Y position for the drag start.\n *\n * @returns A promise which resolves to the result of the drag.\n *\n * #### Notes\n * If the drag has already been started, the promise created by the\n * first call to `start` is returned.\n *\n * If the drag operation has ended, or if the drag object has been\n * disposed, the returned promise will resolve to `'none'`.\n *\n * The drag object will be automatically disposed when drag operation\n * completes. This means `Drag` objects are for single-use only.\n *\n * This method assumes the left mouse button is already held down.\n */\n start(clientX, clientY) {\n // If the drag object is already disposed, resolve to `none`.\n if (this._disposed) {\n return Promise.resolve('none');\n }\n // If the drag has already been started, return the promise.\n if (this._promise) {\n return this._promise;\n }\n // Install the document listeners for the drag object.\n this._addListeners();\n // Attach the drag image at the specified client position.\n this._attachDragImage(clientX, clientY);\n // Create the promise which will be resolved on completion.\n this._promise = new Promise(resolve => {\n this._resolve = resolve;\n });\n // Trigger a fake move event to kick off the drag operation.\n let event = new PointerEvent('pointermove', {\n bubbles: true,\n cancelable: true,\n clientX,\n clientY\n });\n document.dispatchEvent(event);\n // Return the pending promise for the drag operation.\n return this._promise;\n }\n /**\n * Handle the DOM events for the drag operation.\n *\n * @param event - The DOM event sent to the drag object.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the document. It should not be\n * called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n default:\n // Stop all other events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * Move the drag image element to the specified location.\n *\n * This is a no-op if there is no drag image element.\n */\n moveDragImage(clientX, clientY) {\n if (!this.dragImage) {\n return;\n }\n let style = this.dragImage.style;\n style.transform = `translate(${clientX}px, ${clientY}px)`;\n }\n /**\n * Handle the `'pointermove'` event for the drag object.\n */\n _evtPointerMove(event) {\n // Stop all input events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n // Update the current target node and dispatch enter/leave events.\n this._updateCurrentTarget(event);\n // Update the drag scroll element.\n this._updateDragScroll(event);\n // Move the drag image to the specified client position. This is\n // performed *after* dispatching to prevent unnecessary reflows.\n this.moveDragImage(event.clientX, event.clientY);\n }\n /**\n * Handle the `'pointerup'` event for the drag object.\n */\n _evtPointerUp(event) {\n // Stop all input events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n // Do nothing if the left button is not released.\n if (event.button !== 0) {\n return;\n }\n // Update the current target node and dispatch enter/leave events.\n // This prevents a subtle issue where the DOM mutates under the\n // cursor after the last move event but before the drop event.\n this._updateCurrentTarget(event);\n // If there is no current target, finalize with `'none'`.\n if (!this._currentTarget) {\n this._finalize('none');\n return;\n }\n // If the last drop action was `'none'`, dispatch a leave event\n // to the current target and finalize the drag with `'none'`.\n if (this._dropAction === 'none') {\n Private.dispatchDragLeave(this, this._currentTarget, null, event);\n this._finalize('none');\n return;\n }\n // Dispatch the drop event at the current target and finalize\n // with the resulting drop action.\n let action = Private.dispatchDrop(this, this._currentTarget, event);\n this._finalize(action);\n }\n /**\n * Handle the `'keydown'` event for the drag object.\n */\n _evtKeyDown(event) {\n // Stop all input events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n // Cancel the drag if `Escape` is pressed.\n if (event.keyCode === 27) {\n this.dispose();\n }\n }\n /**\n * Add the document event listeners for the drag object.\n */\n _addListeners() {\n document.addEventListener('pointerdown', this, true);\n document.addEventListener('pointermove', this, true);\n document.addEventListener('pointerup', this, true);\n document.addEventListener('pointerenter', this, true);\n document.addEventListener('pointerleave', this, true);\n document.addEventListener('pointerover', this, true);\n document.addEventListener('pointerout', this, true);\n document.addEventListener('keydown', this, true);\n document.addEventListener('keyup', this, true);\n document.addEventListener('keypress', this, true);\n document.addEventListener('contextmenu', this, true);\n }\n /**\n * Remove the document event listeners for the drag object.\n */\n _removeListeners() {\n document.removeEventListener('pointerdown', this, true);\n document.removeEventListener('pointermove', this, true);\n document.removeEventListener('pointerup', this, true);\n document.removeEventListener('pointerenter', this, true);\n document.removeEventListener('pointerleave', this, true);\n document.removeEventListener('pointerover', this, true);\n document.removeEventListener('pointerout', this, true);\n document.removeEventListener('keydown', this, true);\n document.removeEventListener('keyup', this, true);\n document.removeEventListener('keypress', this, true);\n document.removeEventListener('contextmenu', this, true);\n }\n /**\n * Update the drag scroll element under the mouse.\n */\n _updateDragScroll(event) {\n // Find the scroll target under the mouse.\n let target = Private.findScrollTarget(event);\n // Bail if there is nothing to scroll.\n if (!this._scrollTarget && !target) {\n return;\n }\n // Start the scroll loop if needed.\n if (!this._scrollTarget) {\n setTimeout(this._onScrollFrame, 500);\n }\n // Update the scroll target.\n this._scrollTarget = target;\n }\n /**\n * Update the current target node using the given mouse event.\n */\n _updateCurrentTarget(event) {\n // Fetch common local state.\n let prevTarget = this._currentTarget;\n let currTarget = this._currentTarget;\n let prevElem = this._currentElement;\n // Find the current indicated element at the given position.\n let currElem = Private.findElementBehindBackdrop(event, this.document);\n // Update the current element reference.\n this._currentElement = currElem;\n // If the indicated element changes from the previous iteration,\n // and is different from the current target, dispatch the exit\n // event to the target.\n if (currElem !== prevElem && currElem !== currTarget) {\n Private.dispatchDragExit(this, currTarget, currElem, event);\n }\n // If the indicated element changes from the previous iteration,\n // and is different from the current target, dispatch the enter\n // event and compute the new target element.\n if (currElem !== prevElem && currElem !== currTarget) {\n currTarget = Private.dispatchDragEnter(this, currElem, currTarget, event);\n }\n // If the current target element has changed, update the current\n // target reference and dispatch the leave event to the old target.\n if (currTarget !== prevTarget) {\n this._currentTarget = currTarget;\n Private.dispatchDragLeave(this, prevTarget, currTarget, event);\n }\n // Dispatch the drag over event and update the drop action.\n let action = Private.dispatchDragOver(this, currTarget, event);\n this._setDropAction(action);\n }\n /**\n * Attach the drag image element at the specified location.\n *\n * This is a no-op if there is no drag image element.\n */\n _attachDragImage(clientX, clientY) {\n if (!this.dragImage) {\n return;\n }\n this.dragImage.classList.add('lm-mod-drag-image');\n let style = this.dragImage.style;\n style.pointerEvents = 'none';\n style.position = 'fixed';\n style.transform = `translate(${clientX}px, ${clientY}px)`;\n const body = this.document instanceof Document\n ? this.document.body\n : this.document.firstElementChild;\n body.appendChild(this.dragImage);\n }\n /**\n * Detach the drag image element from the DOM.\n *\n * This is a no-op if there is no drag image element.\n */\n _detachDragImage() {\n if (!this.dragImage) {\n return;\n }\n let parent = this.dragImage.parentNode;\n if (!parent) {\n return;\n }\n parent.removeChild(this.dragImage);\n }\n /**\n * Set the internal drop action state and update the drag cursor.\n */\n _setDropAction(action) {\n action = Private.validateAction(action, this.supportedActions);\n if (this._override && this._dropAction === action) {\n return;\n }\n switch (action) {\n case 'none':\n this._dropAction = action;\n this._override = Drag.overrideCursor('no-drop', this.document);\n break;\n case 'copy':\n this._dropAction = action;\n this._override = Drag.overrideCursor('copy', this.document);\n break;\n case 'link':\n this._dropAction = action;\n this._override = Drag.overrideCursor('alias', this.document);\n break;\n case 'move':\n this._dropAction = action;\n this._override = Drag.overrideCursor('move', this.document);\n break;\n }\n }\n /**\n * Finalize the drag operation and resolve the drag promise.\n */\n _finalize(action) {\n // Store the resolve function as a temp variable.\n let resolve = this._resolve;\n // Remove the document event listeners.\n this._removeListeners();\n // Detach the drag image.\n this._detachDragImage();\n // Dispose of the cursor override.\n if (this._override) {\n this._override.dispose();\n this._override = null;\n }\n // Clear the mime data.\n this.mimeData.clear();\n // Clear the rest of the internal drag state.\n this._disposed = true;\n this._dropAction = 'none';\n this._currentTarget = null;\n this._currentElement = null;\n this._scrollTarget = null;\n this._promise = null;\n this._resolve = null;\n // Finally, resolve the promise to the given drop action.\n if (resolve) {\n resolve(action);\n }\n }\n}\n/**\n * The namespace for the `Drag` class statics.\n */\n(function (Drag) {\n /**\n * A custom event used for drag-drop operations.\n *\n * #### Notes\n * In order to receive `'lm-dragover'`, `'lm-dragleave'`, or `'lm-drop'`\n * events, a drop target must cancel the `'lm-dragenter'` event by\n * calling the event's `preventDefault()` method.\n */\n class Event extends DragEvent {\n constructor(event, options) {\n super(options.type, {\n bubbles: true,\n cancelable: true,\n altKey: event.altKey,\n button: event.button,\n clientX: event.clientX,\n clientY: event.clientY,\n ctrlKey: event.ctrlKey,\n detail: 0,\n metaKey: event.metaKey,\n relatedTarget: options.related,\n screenX: event.screenX,\n screenY: event.screenY,\n shiftKey: event.shiftKey,\n view: window\n });\n const { drag } = options;\n this.dropAction = 'none';\n this.mimeData = drag.mimeData;\n this.proposedAction = drag.proposedAction;\n this.supportedActions = drag.supportedActions;\n this.source = drag.source;\n }\n }\n Drag.Event = Event;\n /**\n * Override the cursor icon for the entire document.\n *\n * @param cursor - The string representing the cursor style.\n *\n * @returns A disposable which will clear the override when disposed.\n *\n * #### Notes\n * The most recent call to `overrideCursor` takes precedence.\n * Disposing an old override has no effect on the current override.\n *\n * This utility function is used by the `Drag` class to override the\n * mouse cursor during a drag-drop operation, but it can also be used\n * by other classes to fix the cursor icon during normal mouse drags.\n *\n * #### Example\n * ```typescript\n * import { Drag } from '@lumino/dragdrop';\n *\n * // Force the cursor to be 'wait' for the entire document.\n * let override = Drag.overrideCursor('wait');\n *\n * // Clear the override by disposing the return value.\n * override.dispose();\n * ```\n */\n function overrideCursor(cursor, doc = document) {\n return Private.overrideCursor(cursor, doc);\n }\n Drag.overrideCursor = overrideCursor;\n})(Drag || (Drag = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The size of a drag scroll edge, in pixels.\n */\n Private.SCROLL_EDGE_SIZE = 20;\n /**\n * Validate the given action is one of the supported actions.\n *\n * Returns the given action or `'none'` if the action is unsupported.\n */\n function validateAction(action, supported) {\n return actionTable[action] & supportedTable[supported] ? action : 'none';\n }\n Private.validateAction = validateAction;\n /**\n * Find the event target using pointer position if given, or otherwise\n * the central position of the backdrop.\n */\n function findElementBehindBackdrop(event, root = document) {\n if (event) {\n // Check if we already cached element for this event.\n if (lastElementEventSearch && event == lastElementEventSearch.event) {\n return lastElementEventSearch.element;\n }\n Private.cursorBackdrop.style.zIndex = '-1000';\n const element = root.elementFromPoint(event.clientX, event.clientY);\n Private.cursorBackdrop.style.zIndex = '';\n lastElementEventSearch = { event, element };\n return element;\n }\n else {\n const transform = Private.cursorBackdrop.style.transform;\n if (lastElementSearch && transform === lastElementSearch.transform) {\n return lastElementSearch.element;\n }\n const bbox = Private.cursorBackdrop.getBoundingClientRect();\n Private.cursorBackdrop.style.zIndex = '-1000';\n const element = root.elementFromPoint(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);\n Private.cursorBackdrop.style.zIndex = '';\n lastElementSearch = { transform, element };\n return element;\n }\n }\n Private.findElementBehindBackdrop = findElementBehindBackdrop;\n let lastElementEventSearch = null;\n let lastElementSearch = null;\n /**\n * Find the drag scroll target under the mouse, if any.\n */\n function findScrollTarget(event) {\n // Look up the client mouse position.\n let x = event.clientX;\n let y = event.clientY;\n // Get the element under the mouse.\n let element = findElementBehindBackdrop(event);\n // Search for a scrollable target based on the mouse position.\n // The null assert in third clause of for-loop is required due to:\n // https://github.com/Microsoft/TypeScript/issues/14143\n for (; element; element = element.parentElement) {\n // Ignore elements which are not marked as scrollable.\n if (!element.hasAttribute('data-lm-dragscroll')) {\n continue;\n }\n // Set up the coordinate offsets for the element.\n let offsetX = 0;\n let offsetY = 0;\n if (element === document.body) {\n offsetX = window.pageXOffset;\n offsetY = window.pageYOffset;\n }\n // Get the element bounds in viewport coordinates.\n let r = element.getBoundingClientRect();\n let top = r.top + offsetY;\n let left = r.left + offsetX;\n let right = left + r.width;\n let bottom = top + r.height;\n // Skip the element if it's not under the mouse.\n if (x < left || x >= right || y < top || y >= bottom) {\n continue;\n }\n // Compute the distance to each edge.\n let dl = x - left + 1;\n let dt = y - top + 1;\n let dr = right - x;\n let db = bottom - y;\n // Find the smallest of the edge distances.\n let distance = Math.min(dl, dt, dr, db);\n // Skip the element if the mouse is not within a scroll edge.\n if (distance > Private.SCROLL_EDGE_SIZE) {\n continue;\n }\n // Set up the edge result variable.\n let edge;\n // Find the edge for the computed distance.\n switch (distance) {\n case db:\n edge = 'bottom';\n break;\n case dt:\n edge = 'top';\n break;\n case dr:\n edge = 'right';\n break;\n case dl:\n edge = 'left';\n break;\n default:\n throw 'unreachable';\n }\n // Compute how much the element can scroll in width and height.\n let dsw = element.scrollWidth - element.clientWidth;\n let dsh = element.scrollHeight - element.clientHeight;\n // Determine if the element should be scrolled for the edge.\n let shouldScroll;\n switch (edge) {\n case 'top':\n shouldScroll = dsh > 0 && element.scrollTop > 0;\n break;\n case 'left':\n shouldScroll = dsw > 0 && element.scrollLeft > 0;\n break;\n case 'right':\n shouldScroll = dsw > 0 && element.scrollLeft < dsw;\n break;\n case 'bottom':\n shouldScroll = dsh > 0 && element.scrollTop < dsh;\n break;\n default:\n throw 'unreachable';\n }\n // Skip the element if it should not be scrolled.\n if (!shouldScroll) {\n continue;\n }\n // Return the drag scroll target.\n return { element, edge, distance };\n }\n // No drag scroll target was found.\n return null;\n }\n Private.findScrollTarget = findScrollTarget;\n /**\n * Dispatch a drag enter event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param currElem - The currently indicated element, or `null`. This\n * is the \"immediate user selection\" from the whatwg spec.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * @returns The element to use as the current drag target. This is the\n * \"current target element\" from the whatwg spec, and may be `null`.\n *\n * #### Notes\n * This largely implements the drag enter portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragEnter(drag, currElem, currTarget, event) {\n // If the current element is null, return null as the new target.\n if (!currElem) {\n return null;\n }\n // Dispatch a drag enter event to the current element.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragenter'\n });\n let canceled = !currElem.dispatchEvent(dragEvent);\n // If the event was canceled, use the current element as the new target.\n if (canceled) {\n return currElem;\n }\n // If the current element is the document body, keep the original target.\n const body = drag.document instanceof Document\n ? drag.document.body\n : drag.document.firstElementChild;\n if (currElem === body) {\n return currTarget;\n }\n // Dispatch a drag enter event on the document body.\n dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragenter'\n });\n body.dispatchEvent(dragEvent);\n // Ignore the event cancellation, and use the body as the new target.\n return body;\n }\n Private.dispatchDragEnter = dispatchDragEnter;\n /**\n * Dispatch a drag exit event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param prevTarget - The previous target element, or `null`. This\n * is the previous \"current target element\" from the whatwg spec.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * #### Notes\n * This largely implements the drag exit portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragExit(drag, prevTarget, currTarget, event) {\n // If the previous target is null, do nothing.\n if (!prevTarget) {\n return;\n }\n // Dispatch the drag exit event to the previous target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragexit'\n });\n prevTarget.dispatchEvent(dragEvent);\n }\n Private.dispatchDragExit = dispatchDragExit;\n /**\n * Dispatch a drag leave event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param prevTarget - The previous target element, or `null`. This\n * is the previous \"current target element\" from the whatwg spec.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * #### Notes\n * This largely implements the drag leave portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragLeave(drag, prevTarget, currTarget, event) {\n // If the previous target is null, do nothing.\n if (!prevTarget) {\n return;\n }\n // Dispatch the drag leave event to the previous target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragleave'\n });\n prevTarget.dispatchEvent(dragEvent);\n }\n Private.dispatchDragLeave = dispatchDragLeave;\n /**\n * Dispatch a drag over event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * @returns The `DropAction` result of the drag over event.\n *\n * #### Notes\n * This largely implements the drag over portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragOver(drag, currTarget, event) {\n // If there is no current target, the drop action is none.\n if (!currTarget) {\n return 'none';\n }\n // Dispatch the drag over event to the current target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: null,\n type: 'lm-dragover'\n });\n let canceled = !currTarget.dispatchEvent(dragEvent);\n // If the event was canceled, return the drop action result.\n if (canceled) {\n return dragEvent.dropAction;\n }\n // Otherwise, the effective drop action is none.\n return 'none';\n }\n Private.dispatchDragOver = dispatchDragOver;\n /**\n * Dispatch a drop event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * @returns The `DropAction` result of the drop event.\n *\n * #### Notes\n * This largely implements the drag over portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDrop(drag, currTarget, event) {\n // If there is no current target, the drop action is none.\n if (!currTarget) {\n return 'none';\n }\n // Dispatch the drop event to the current target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: null,\n type: 'lm-drop'\n });\n let canceled = !currTarget.dispatchEvent(dragEvent);\n // If the event was canceled, return the drop action result.\n if (canceled) {\n return dragEvent.dropAction;\n }\n // Otherwise, the effective drop action is none.\n return 'none';\n }\n Private.dispatchDrop = dispatchDrop;\n /**\n * A lookup table from drop action to bit value.\n */\n const actionTable = {\n none: 0x0,\n copy: 0x1,\n link: 0x2,\n move: 0x4\n };\n /**\n * A lookup table from supported action to drop action bit mask.\n */\n const supportedTable = {\n none: actionTable['none'],\n copy: actionTable['copy'],\n link: actionTable['link'],\n move: actionTable['move'],\n 'copy-link': actionTable['copy'] | actionTable['link'],\n 'copy-move': actionTable['copy'] | actionTable['move'],\n 'link-move': actionTable['link'] | actionTable['move'],\n all: actionTable['copy'] | actionTable['link'] | actionTable['move']\n };\n /**\n * Implementation of `Drag.overrideCursor`.\n */\n function overrideCursor(cursor, doc = document) {\n let id = ++overrideCursorID;\n const body = doc instanceof Document\n ? doc.body\n : doc.firstElementChild;\n if (!Private.cursorBackdrop.isConnected) {\n // Hide the backdrop until the pointer moves to avoid issues with\n // native double click detection, used in e.g. datagrid editing.\n Private.cursorBackdrop.style.transform = 'scale(0)';\n body.appendChild(Private.cursorBackdrop);\n resetBackdropScroll();\n document.addEventListener('pointermove', alignBackdrop, {\n capture: true,\n passive: true\n });\n Private.cursorBackdrop.addEventListener('scroll', propagateBackdropScroll, {\n capture: true,\n passive: true\n });\n }\n Private.cursorBackdrop.style.cursor = cursor;\n return new DisposableDelegate(() => {\n if (id === overrideCursorID && Private.cursorBackdrop.isConnected) {\n document.removeEventListener('pointermove', alignBackdrop, true);\n Private.cursorBackdrop.removeEventListener('scroll', propagateBackdropScroll, true);\n body.removeChild(Private.cursorBackdrop);\n }\n });\n }\n Private.overrideCursor = overrideCursor;\n /**\n * Move cursor backdrop to match cursor position.\n */\n function alignBackdrop(event) {\n if (!Private.cursorBackdrop) {\n return;\n }\n Private.cursorBackdrop.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;\n }\n /**\n * Propagate the scroll event from the backdrop element to the scroll target.\n * The scroll target is defined by presence of `data-lm-dragscroll` attribute.\n */\n function propagateBackdropScroll(_event) {\n if (!Private.cursorBackdrop) {\n return;\n }\n // Get the element under behind the centre of the cursor backdrop\n // (essentially behind the cursor, but possibly a few pixels off).\n let element = findElementBehindBackdrop();\n if (!element) {\n return;\n }\n // Find scroll target.\n const scrollTarget = element.closest('[data-lm-dragscroll]');\n if (!scrollTarget) {\n return;\n }\n // Apply the scroll delta to the correct target.\n scrollTarget.scrollTop += Private.cursorBackdrop.scrollTop - backdropScrollOrigin;\n scrollTarget.scrollLeft += Private.cursorBackdrop.scrollLeft - backdropScrollOrigin;\n // Center the scroll position.\n resetBackdropScroll();\n }\n /**\n * Reset the backdrop scroll to allow further scrolling.\n */\n function resetBackdropScroll() {\n Private.cursorBackdrop.scrollTop = backdropScrollOrigin;\n Private.cursorBackdrop.scrollLeft = backdropScrollOrigin;\n }\n /**\n * The center of the backdrop node scroll area.\n */\n const backdropScrollOrigin = 500;\n /**\n * Create cursor backdrop node.\n */\n function createCursorBackdrop() {\n const backdrop = document.createElement('div');\n backdrop.classList.add('lm-cursor-backdrop');\n return backdrop;\n }\n /**\n * The internal id for the active cursor override.\n */\n let overrideCursorID = 0;\n /**\n * A backdrop node overriding pointer cursor.\n *\n * #### Notes\n * We use a backdrop node rather than setting the cursor directly on the body\n * because setting it on body requires more extensive style recalculation for\n * reliable application of the cursor, this is the cursor not being overriden\n * when over child elements with another style like `cursor: other!important`.\n */\n Private.cursorBackdrop = createCursorBackdrop();\n})(Private || (Private = {}));\n\nexport { Drag };\n//# sourceMappingURL=index.es6.js.map\n","import { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\n/**\n * A disposable object which delegates to a callback function.\n */\nclass DisposableDelegate {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn) {\n this._fn = fn;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return !this._fn;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n}\n/**\n * An observable disposable object which delegates to a callback function.\n */\nclass ObservableDisposableDelegate extends DisposableDelegate {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * An object which manages a collection of disposable items.\n */\nclass DisposableSet {\n constructor() {\n this._isDisposed = false;\n this._items = new Set();\n }\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item) {\n return this._items.has(item);\n }\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item) {\n this._items.add(item);\n }\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item) {\n this._items.delete(item);\n }\n /**\n * Remove all items from the set.\n */\n clear() {\n this._items.clear();\n }\n}\n/**\n * The namespace for the `DisposableSet` class statics.\n */\n(function (DisposableSet) {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n DisposableSet.from = from;\n})(DisposableSet || (DisposableSet = {}));\n/**\n * An observable object which manages a collection of disposable items.\n */\nclass ObservableDisposableSet extends DisposableSet {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\n(function (ObservableDisposableSet) {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n ObservableDisposableSet.from = from;\n})(ObservableDisposableSet || (ObservableDisposableSet = {}));\n\nexport { DisposableDelegate, DisposableSet, ObservableDisposableDelegate, ObservableDisposableSet };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module keyboard\n */\n/**\n * Get the global application keyboard layout instance.\n *\n * @returns The keyboard layout for use by the application.\n *\n * #### Notes\n * The default keyboard layout is US-English.\n */\nfunction getKeyboardLayout() {\n return Private.keyboardLayout;\n}\n/**\n * Set the global application keyboard layout instance.\n *\n * @param - The keyboard layout for use by the application.\n *\n * #### Notes\n * The keyboard layout should typically be set on application startup\n * to a layout which is appropriate for the user's system.\n */\nfunction setKeyboardLayout(layout) {\n Private.keyboardLayout = layout;\n}\n/**\n * A concrete implementation of {@link IKeyboardLayout} based on keycodes.\n *\n * The `keyCode` property of a `'keydown'` event is a browser and OS\n * specific representation of the physical key (not character) which\n * was pressed on a keyboard. While not the most convenient API, it\n * is currently the only one which works reliably on all browsers.\n *\n * This class accepts a user-defined mapping of keycode to key, which\n * allows for reliable shortcuts tailored to the user's system.\n */\nclass KeycodeLayout {\n /**\n * Construct a new keycode layout.\n *\n * @param name - The human readable name for the layout.\n *\n * @param codes - A mapping of keycode to key value.\n *\n * @param modifierKeys - Array of modifier key names\n */\n constructor(name, codes, modifierKeys = []) {\n this.name = name;\n this._codes = codes;\n this._keys = KeycodeLayout.extractKeys(codes);\n this._modifierKeys = KeycodeLayout.convertToKeySet(modifierKeys);\n }\n /**\n * Get an array of the key values supported by the layout.\n *\n * @returns A new array of the supported key values.\n */\n keys() {\n return Object.keys(this._keys);\n }\n /**\n * Test whether the given key is a valid value for the layout.\n *\n * @param key - The user provided key to test for validity.\n *\n * @returns `true` if the key is valid, `false` otherwise.\n */\n isValidKey(key) {\n return key in this._keys;\n }\n /**\n * Test whether the given key is a modifier key.\n *\n * @param key - The user provided key.\n *\n * @returns `true` if the key is a modifier key, `false` otherwise.\n */\n isModifierKey(key) {\n return key in this._modifierKeys;\n }\n /**\n * Get the key for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns The associated key value, or an empty string if\n * the event does not represent a valid primary key.\n */\n keyForKeydownEvent(event) {\n return this._codes[event.keyCode] || '';\n }\n}\n/**\n * The namespace for the `KeycodeLayout` class statics.\n */\n(function (KeycodeLayout) {\n /**\n * Extract the set of keys from a code map.\n *\n * @param code - The code map of interest.\n *\n * @returns A set of the keys in the code map.\n */\n function extractKeys(codes) {\n let keys = Object.create(null);\n for (let c in codes) {\n keys[codes[c]] = true;\n }\n return keys;\n }\n KeycodeLayout.extractKeys = extractKeys;\n /**\n * Convert array of keys to a key set.\n *\n * @param keys - The array that needs to be converted\n *\n * @returns A set of the keys in the array.\n */\n function convertToKeySet(keys) {\n let keySet = Object(null);\n for (let i = 0, n = keys.length; i < n; ++i) {\n keySet[keys[i]] = true;\n }\n return keySet;\n }\n KeycodeLayout.convertToKeySet = convertToKeySet;\n})(KeycodeLayout || (KeycodeLayout = {}));\n/**\n * A keycode-based keyboard layout for US English keyboards.\n *\n * This layout is valid for the following OS/Browser combinations.\n *\n * - Windows\n * - Chrome\n * - Firefox\n * - IE\n *\n * - OSX\n * - Chrome\n * - Firefox\n * - Safari\n *\n * - Linux\n * - Chrome\n * - Firefox\n *\n * Other combinations may also work, but are untested.\n */\nconst EN_US = new KeycodeLayout('en-us', {\n 8: 'Backspace',\n 9: 'Tab',\n 13: 'Enter',\n 16: 'Shift',\n 17: 'Ctrl',\n 18: 'Alt',\n 19: 'Pause',\n 27: 'Escape',\n 32: 'Space',\n 33: 'PageUp',\n 34: 'PageDown',\n 35: 'End',\n 36: 'Home',\n 37: 'ArrowLeft',\n 38: 'ArrowUp',\n 39: 'ArrowRight',\n 40: 'ArrowDown',\n 45: 'Insert',\n 46: 'Delete',\n 48: '0',\n 49: '1',\n 50: '2',\n 51: '3',\n 52: '4',\n 53: '5',\n 54: '6',\n 55: '7',\n 56: '8',\n 57: '9',\n 59: ';',\n 61: '=',\n 65: 'A',\n 66: 'B',\n 67: 'C',\n 68: 'D',\n 69: 'E',\n 70: 'F',\n 71: 'G',\n 72: 'H',\n 73: 'I',\n 74: 'J',\n 75: 'K',\n 76: 'L',\n 77: 'M',\n 78: 'N',\n 79: 'O',\n 80: 'P',\n 81: 'Q',\n 82: 'R',\n 83: 'S',\n 84: 'T',\n 85: 'U',\n 86: 'V',\n 87: 'W',\n 88: 'X',\n 89: 'Y',\n 90: 'Z',\n 91: 'Meta',\n 93: 'ContextMenu',\n 96: '0',\n 97: '1',\n 98: '2',\n 99: '3',\n 100: '4',\n 101: '5',\n 102: '6',\n 103: '7',\n 104: '8',\n 105: '9',\n 106: '*',\n 107: '+',\n 109: '-',\n 110: '.',\n 111: '/',\n 112: 'F1',\n 113: 'F2',\n 114: 'F3',\n 115: 'F4',\n 116: 'F5',\n 117: 'F6',\n 118: 'F7',\n 119: 'F8',\n 120: 'F9',\n 121: 'F10',\n 122: 'F11',\n 123: 'F12',\n 173: '-',\n 186: ';',\n 187: '=',\n 188: ',',\n 189: '-',\n 190: '.',\n 191: '/',\n 192: '`',\n 219: '[',\n 220: '\\\\',\n 221: ']',\n 222: \"'\",\n 224: 'Meta' // firefox\n}, ['Shift', 'Ctrl', 'Alt', 'Meta'] // modifier keys\n);\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The global keyboard layout instance.\n */\n Private.keyboardLayout = EN_US;\n})(Private || (Private = {}));\n\nexport { EN_US, KeycodeLayout, getKeyboardLayout, setKeyboardLayout };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt } from '@lumino/algorithm';\nimport { JSONExt } from '@lumino/coreutils';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport { Platform, Selector } from '@lumino/domutils';\nimport { getKeyboardLayout } from '@lumino/keyboard';\nimport { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module commands\n */\n/**\n * An object which manages a collection of commands.\n *\n * #### Notes\n * A command registry can be used to populate a variety of action-based\n * widgets, such as command palettes, menus, and toolbars.\n */\nclass CommandRegistry {\n constructor() {\n this._timerID = 0;\n this._replaying = false;\n this._keystrokes = [];\n this._keydownEvents = [];\n this._keyBindings = [];\n this._exactKeyMatch = null;\n this._commands = new Map();\n this._commandChanged = new Signal(this);\n this._commandExecuted = new Signal(this);\n this._keyBindingChanged = new Signal(this);\n }\n /**\n * A signal emitted when a command has changed.\n *\n * #### Notes\n * This signal is useful for visual representations of commands which\n * need to refresh when the state of a relevant command has changed.\n */\n get commandChanged() {\n return this._commandChanged;\n }\n /**\n * A signal emitted when a command has executed.\n *\n * #### Notes\n * Care should be taken when consuming this signal. The command system is used\n * by many components for many user actions. Handlers registered with this\n * signal must return quickly to ensure the overall application remains responsive.\n */\n get commandExecuted() {\n return this._commandExecuted;\n }\n /**\n * A signal emitted when a key binding is changed.\n */\n get keyBindingChanged() {\n return this._keyBindingChanged;\n }\n /**\n * A read-only array of the key bindings in the registry.\n */\n get keyBindings() {\n return this._keyBindings;\n }\n /**\n * List the ids of the registered commands.\n *\n * @returns A new array of the registered command ids.\n */\n listCommands() {\n return Array.from(this._commands.keys());\n }\n /**\n * Test whether a specific command is registered.\n *\n * @param id - The id of the command of interest.\n *\n * @returns `true` if the command is registered, `false` otherwise.\n */\n hasCommand(id) {\n return this._commands.has(id);\n }\n /**\n * Add a command to the registry.\n *\n * @param id - The unique id of the command.\n *\n * @param options - The options for the command.\n *\n * @returns A disposable which will remove the command.\n *\n * @throws An error if the given `id` is already registered.\n */\n addCommand(id, options) {\n // Throw an error if the id is already registered.\n if (this._commands.has(id)) {\n throw new Error(`Command '${id}' already registered.`);\n }\n // Add the command to the registry.\n this._commands.set(id, Private.createCommand(options));\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'added' });\n // Return a disposable which will remove the command.\n return new DisposableDelegate(() => {\n // Remove the command from the registry.\n this._commands.delete(id);\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'removed' });\n });\n }\n /**\n * Notify listeners that the state of a command has changed.\n *\n * @param id - The id of the command which has changed. If more than\n * one command has changed, this argument should be omitted.\n *\n * @throws An error if the given `id` is not registered.\n *\n * #### Notes\n * This method should be called by the command author whenever the\n * application state changes such that the results of the command\n * metadata functions may have changed.\n *\n * This will cause the `commandChanged` signal to be emitted.\n */\n notifyCommandChanged(id) {\n if (id !== undefined && !this._commands.has(id)) {\n throw new Error(`Command '${id}' is not registered.`);\n }\n this._commandChanged.emit({ id, type: id ? 'changed' : 'many-changed' });\n }\n /**\n * Get the description for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The description for the command.\n */\n describedBy(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return Promise.resolve((_a = cmd === null || cmd === void 0 ? void 0 : cmd.describedBy.call(undefined, args)) !== null && _a !== void 0 ? _a : { args: null });\n }\n /**\n * Get the display label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The display label for the command, or an empty string\n * if the command is not registered.\n */\n label(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return (_a = cmd === null || cmd === void 0 ? void 0 : cmd.label.call(undefined, args)) !== null && _a !== void 0 ? _a : '';\n }\n /**\n * Get the mnemonic index for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The mnemonic index for the command, or `-1` if the\n * command is not registered.\n */\n mnemonic(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.mnemonic.call(undefined, args) : -1;\n }\n /**\n * Get the icon renderer for a specific command.\n *\n * DEPRECATED: if set to a string value, the .icon field will\n * function as an alias for the .iconClass field, for backwards\n * compatibility. In the future when this is removed, the default\n * return type will become undefined.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon renderer for the command or `undefined`.\n */\n icon(id, args = JSONExt.emptyObject) {\n var _a;\n return (_a = this._commands.get(id)) === null || _a === void 0 ? void 0 : _a.icon.call(undefined, args);\n }\n /**\n * Get the icon class for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon class for the command, or an empty string if\n * the command is not registered.\n */\n iconClass(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconClass.call(undefined, args) : '';\n }\n /**\n * Get the icon label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon label for the command, or an empty string if\n * the command is not registered.\n */\n iconLabel(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconLabel.call(undefined, args) : '';\n }\n /**\n * Get the short form caption for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The caption for the command, or an empty string if the\n * command is not registered.\n */\n caption(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.caption.call(undefined, args) : '';\n }\n /**\n * Get the usage help text for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The usage text for the command, or an empty string if\n * the command is not registered.\n */\n usage(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.usage.call(undefined, args) : '';\n }\n /**\n * Get the extra class name for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The class name for the command, or an empty string if\n * the command is not registered.\n */\n className(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.className.call(undefined, args) : '';\n }\n /**\n * Get the dataset for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The dataset for the command, or an empty dataset if\n * the command is not registered.\n */\n dataset(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.dataset.call(undefined, args) : {};\n }\n /**\n * Test whether a specific command is enabled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is enabled,\n * or `false` if the command is not registered.\n */\n isEnabled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isEnabled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggled,\n * or `false` if the command is not registered.\n */\n isToggled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggleable.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggleable,\n * or `false` if the command is not registered.\n */\n isToggleable(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggleable : false;\n }\n /**\n * Test whether a specific command is visible.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is visible,\n * or `false` if the command is not registered.\n */\n isVisible(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isVisible.call(undefined, args) : false;\n }\n /**\n * Execute a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A promise which resolves with the result of the command.\n *\n * #### Notes\n * The promise will reject if the command throws an exception,\n * or if the command is not registered.\n */\n execute(id, args = JSONExt.emptyObject) {\n // Reject if the command is not registered.\n let cmd = this._commands.get(id);\n if (!cmd) {\n return Promise.reject(new Error(`Command '${id}' not registered.`));\n }\n // Execute the command and reject if an exception is thrown.\n let value;\n try {\n value = cmd.execute.call(undefined, args);\n }\n catch (err) {\n value = Promise.reject(err);\n }\n // Create the return promise which resolves the result.\n let result = Promise.resolve(value);\n // Emit the command executed signal.\n this._commandExecuted.emit({ id, args, result });\n // Return the result promise to the caller.\n return result;\n }\n /**\n * Add a key binding to the registry.\n *\n * @param options - The options for creating the key binding.\n *\n * @returns A disposable which removes the added key binding.\n *\n * #### Notes\n * If multiple key bindings are registered for the same sequence, the\n * binding with the highest selector specificity is executed first. A\n * tie is broken by using the most recently added key binding.\n *\n * Ambiguous key bindings are resolved with a timeout. As an example,\n * suppose two key bindings are registered: one with the key sequence\n * `['Ctrl D']`, and another with `['Ctrl D', 'Ctrl W']`. If the user\n * presses `Ctrl D`, the first binding cannot be immediately executed\n * since the user may intend to complete the chord with `Ctrl W`. For\n * such cases, a timer is used to allow the chord to be completed. If\n * the chord is not completed before the timeout, the first binding\n * is executed.\n */\n addKeyBinding(options) {\n // Create the binding for the given options.\n let binding = Private.createKeyBinding(options);\n // Add the key binding to the bindings array.\n this._keyBindings.push(binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'added' });\n // Return a disposable which will remove the binding.\n return new DisposableDelegate(() => {\n // Remove the binding from the array.\n ArrayExt.removeFirstOf(this._keyBindings, binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'removed' });\n });\n }\n /**\n * Process a `'keydown'` event and invoke a matching key binding.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * #### Notes\n * This should be called in response to a `'keydown'` event in order\n * to invoke the command for the best matching key binding.\n *\n * The registry **does not** install its own listener for `'keydown'`\n * events. This allows the application full control over the nodes\n * and phase for which the registry processes `'keydown'` events.\n *\n * When the keydown event is processed, if the event target or any of its\n * ancestor nodes has a `data-lm-suppress-shortcuts` attribute, its keydown\n * events will not invoke commands.\n */\n processKeydownEvent(event) {\n // Bail immediately if playing back keystrokes.\n if (this._replaying || CommandRegistry.isModifierKeyPressed(event)) {\n return;\n }\n // Get the normalized keystroke for the event.\n let keystroke = CommandRegistry.keystrokeForKeydownEvent(event);\n // If the keystroke is not valid for the keyboard layout, replay\n // any suppressed events and clear the pending state.\n if (!keystroke) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Add the keystroke to the current key sequence.\n this._keystrokes.push(keystroke);\n // Find the exact and partial matches for the key sequence.\n let { exact, partial } = Private.matchKeyBinding(this._keyBindings, this._keystrokes, event);\n // If there is no exact match and no partial match, replay\n // any suppressed events and clear the pending state.\n if (!exact && !partial) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Stop propagation of the event. If there is only a partial match,\n // the event will be replayed if a final exact match never occurs.\n event.preventDefault();\n event.stopPropagation();\n // If there is an exact match but no partial match, the exact match\n // can be dispatched immediately. The pending state is cleared so\n // the next key press starts from the default state.\n if (exact && !partial) {\n this._executeKeyBinding(exact);\n this._clearPendingState();\n return;\n }\n // If there is both an exact match and a partial match, the exact\n // match is stored for future dispatch in case the timer expires\n // before a more specific match is triggered.\n if (exact) {\n this._exactKeyMatch = exact;\n }\n // Store the event for possible playback in the future.\n this._keydownEvents.push(event);\n // (Re)start the timer to dispatch the most recent exact match\n // in case the partial match fails to result in an exact match.\n this._startTimer();\n }\n /**\n * Start or restart the pending timeout.\n */\n _startTimer() {\n this._clearTimer();\n this._timerID = window.setTimeout(() => {\n this._onPendingTimeout();\n }, Private.CHORD_TIMEOUT);\n }\n /**\n * Clear the pending timeout.\n */\n _clearTimer() {\n if (this._timerID !== 0) {\n clearTimeout(this._timerID);\n this._timerID = 0;\n }\n }\n /**\n * Replay the keydown events which were suppressed.\n */\n _replayKeydownEvents() {\n if (this._keydownEvents.length === 0) {\n return;\n }\n this._replaying = true;\n this._keydownEvents.forEach(Private.replayKeyEvent);\n this._replaying = false;\n }\n /**\n * Execute the command for the given key binding.\n *\n * If the command is missing or disabled, a warning will be logged.\n */\n _executeKeyBinding(binding) {\n let { command, args } = binding;\n let newArgs = {\n _luminoEvent: { type: 'keybinding', keys: binding.keys },\n ...args\n };\n if (!this.hasCommand(command) || !this.isEnabled(command, newArgs)) {\n let word = this.hasCommand(command) ? 'enabled' : 'registered';\n let keys = binding.keys.join(', ');\n let msg1 = `Cannot execute key binding '${keys}':`;\n let msg2 = `command '${command}' is not ${word}.`;\n console.warn(`${msg1} ${msg2}`);\n return;\n }\n this.execute(command, newArgs);\n }\n /**\n * Clear the internal pending state.\n */\n _clearPendingState() {\n this._clearTimer();\n this._exactKeyMatch = null;\n this._keystrokes.length = 0;\n this._keydownEvents.length = 0;\n }\n /**\n * Handle the partial match timeout.\n */\n _onPendingTimeout() {\n this._timerID = 0;\n if (this._exactKeyMatch) {\n this._executeKeyBinding(this._exactKeyMatch);\n }\n else {\n this._replayKeydownEvents();\n }\n this._clearPendingState();\n }\n}\n/**\n * The namespace for the `CommandRegistry` class statics.\n */\n(function (CommandRegistry) {\n /**\n * Parse a keystroke into its constituent components.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The parsed components of the keystroke.\n *\n * #### Notes\n * The keystroke should be of the form:\n * `[ [ [ ]]]`\n *\n * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and\n * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and\n * `Ctrl` on all other platforms.\n *\n * The parsing is tolerant and will not throw exceptions. Notably:\n * - Duplicate modifiers are ignored.\n * - Extra primary keys are ignored.\n * - The order of modifiers and primary key is irrelevant.\n * - The keystroke parts should be separated by whitespace.\n * - The keystroke is case sensitive.\n */\n function parseKeystroke(keystroke) {\n let key = '';\n let alt = false;\n let cmd = false;\n let ctrl = false;\n let shift = false;\n for (let token of keystroke.split(/\\s+/)) {\n if (token === 'Accel') {\n if (Platform.IS_MAC) {\n cmd = true;\n }\n else {\n ctrl = true;\n }\n }\n else if (token === 'Alt') {\n alt = true;\n }\n else if (token === 'Cmd') {\n cmd = true;\n }\n else if (token === 'Ctrl') {\n ctrl = true;\n }\n else if (token === 'Shift') {\n shift = true;\n }\n else if (token.length > 0) {\n key = token;\n }\n }\n return { cmd, ctrl, alt, shift, key };\n }\n CommandRegistry.parseKeystroke = parseKeystroke;\n /**\n * Normalize a keystroke into a canonical representation.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The normalized representation of the keystroke.\n *\n * #### Notes\n * This normalizes the keystroke by removing duplicate modifiers and\n * extra primary keys, and assembling the parts in a canonical order.\n *\n * The `Cmd` modifier is ignored on non-Mac platforms.\n */\n function normalizeKeystroke(keystroke) {\n let mods = '';\n let parts = parseKeystroke(keystroke);\n if (parts.ctrl) {\n mods += 'Ctrl ';\n }\n if (parts.alt) {\n mods += 'Alt ';\n }\n if (parts.shift) {\n mods += 'Shift ';\n }\n if (parts.cmd && Platform.IS_MAC) {\n mods += 'Cmd ';\n }\n return mods + parts.key;\n }\n CommandRegistry.normalizeKeystroke = normalizeKeystroke;\n /**\n * Get the platform-specific normalized keys for an options object.\n *\n * @param options - The options for the key binding.\n *\n * @returns Array of combined, normalized keys.\n */\n function normalizeKeys(options) {\n let keys;\n if (Platform.IS_WIN) {\n keys = options.winKeys || options.keys;\n }\n else if (Platform.IS_MAC) {\n keys = options.macKeys || options.keys;\n }\n else {\n keys = options.linuxKeys || options.keys;\n }\n return keys.map(normalizeKeystroke);\n }\n CommandRegistry.normalizeKeys = normalizeKeys;\n /**\n * Format keystrokes for display on the local system.\n *\n * If a list of keystrokes is provided, it will be displayed as\n * a comma-separated string\n *\n * @param keystroke The keystrokes to format\n * @returns The keystrokes representation\n */\n function formatKeystroke(keystroke) {\n return typeof keystroke === 'string'\n ? formatSingleKey(keystroke)\n : keystroke.map(formatSingleKey).join(', ');\n function formatSingleKey(key) {\n let mods = [];\n let separator = Platform.IS_MAC ? ' ' : '+';\n let parts = parseKeystroke(key);\n if (parts.ctrl) {\n mods.push('Ctrl');\n }\n if (parts.alt) {\n mods.push('Alt');\n }\n if (parts.shift) {\n mods.push('Shift');\n }\n if (Platform.IS_MAC && parts.cmd) {\n mods.push('Cmd');\n }\n mods.push(parts.key);\n return mods.map(Private.formatKey).join(separator);\n }\n }\n CommandRegistry.formatKeystroke = formatKeystroke;\n /**\n * Check if `'keydown'` event is caused by pressing a modifier key that should be ignored.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns `true` if modifier key was pressed, `false` otherwise.\n */\n function isModifierKeyPressed(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n return layout.isModifierKey(key);\n }\n CommandRegistry.isModifierKeyPressed = isModifierKeyPressed;\n /**\n * Create a normalized keystroke for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns A normalized keystroke, or an empty string if the event\n * does not represent a valid keystroke for the given layout.\n */\n function keystrokeForKeydownEvent(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n if (!key || layout.isModifierKey(key)) {\n return '';\n }\n let mods = [];\n if (event.ctrlKey) {\n mods.push('Ctrl');\n }\n if (event.altKey) {\n mods.push('Alt');\n }\n if (event.shiftKey) {\n mods.push('Shift');\n }\n if (event.metaKey && Platform.IS_MAC) {\n mods.push('Cmd');\n }\n mods.push(key);\n return mods.join(' ');\n }\n CommandRegistry.keystrokeForKeydownEvent = keystrokeForKeydownEvent;\n})(CommandRegistry || (CommandRegistry = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The timeout in ms for triggering a key binding chord.\n */\n Private.CHORD_TIMEOUT = 1000;\n /**\n * Create a normalized command from an options object.\n */\n function createCommand(options) {\n return {\n execute: options.execute,\n describedBy: asFunc(typeof options.describedBy === 'function'\n ? options.describedBy\n : { args: null, ...options.describedBy }, () => {\n return { args: null };\n }),\n label: asFunc(options.label, emptyStringFunc),\n mnemonic: asFunc(options.mnemonic, negativeOneFunc),\n icon: asFunc(options.icon, undefinedFunc),\n iconClass: asFunc(options.iconClass, emptyStringFunc),\n iconLabel: asFunc(options.iconLabel, emptyStringFunc),\n caption: asFunc(options.caption, emptyStringFunc),\n usage: asFunc(options.usage, emptyStringFunc),\n className: asFunc(options.className, emptyStringFunc),\n dataset: asFunc(options.dataset, emptyDatasetFunc),\n isEnabled: options.isEnabled || trueFunc,\n isToggled: options.isToggled || falseFunc,\n isToggleable: options.isToggleable || !!options.isToggled,\n isVisible: options.isVisible || trueFunc\n };\n }\n Private.createCommand = createCommand;\n /**\n * Create a key binding object from key binding options.\n */\n function createKeyBinding(options) {\n return {\n keys: CommandRegistry.normalizeKeys(options),\n selector: validateSelector(options),\n command: options.command,\n args: options.args || JSONExt.emptyObject\n };\n }\n Private.createKeyBinding = createKeyBinding;\n /**\n * Find the key bindings which match a key sequence.\n *\n * This returns a match result which contains the best exact matching\n * binding, and a flag which indicates if there are partial matches.\n */\n function matchKeyBinding(bindings, keys, event) {\n // The current best exact match.\n let exact = null;\n // Whether a partial match has been found.\n let partial = false;\n // The match distance for the exact match.\n let distance = Infinity;\n // The specificity for the exact match.\n let specificity = 0;\n // Iterate over the bindings and search for the best match.\n for (let i = 0, n = bindings.length; i < n; ++i) {\n // Lookup the current binding.\n let binding = bindings[i];\n // Check whether the key binding sequence is a match.\n let sqm = matchSequence(binding.keys, keys);\n // If there is no match, the binding is ignored.\n if (sqm === 0 /* SequenceMatch.None */) {\n continue;\n }\n // If it is a partial match and no other partial match has been\n // found, ensure the selector matches and set the partial flag.\n if (sqm === 2 /* SequenceMatch.Partial */) {\n if (!partial && targetDistance(binding.selector, event) !== -1) {\n partial = true;\n }\n continue;\n }\n // Ignore the match if the selector doesn't match, or if the\n // matched node is farther away than the current best match.\n let td = targetDistance(binding.selector, event);\n if (td === -1 || td > distance) {\n continue;\n }\n // Get the specificity for the selector.\n let sp = Selector.calculateSpecificity(binding.selector);\n // Update the best match if this match is stronger.\n if (!exact || td < distance || sp >= specificity) {\n exact = binding;\n distance = td;\n specificity = sp;\n }\n }\n // Return the match result.\n return { exact, partial };\n }\n Private.matchKeyBinding = matchKeyBinding;\n /**\n * Replay a keyboard event.\n *\n * This synthetically dispatches a clone of the keyboard event.\n */\n function replayKeyEvent(event) {\n event.target.dispatchEvent(cloneKeyboardEvent(event));\n }\n Private.replayKeyEvent = replayKeyEvent;\n function formatKey(key) {\n if (Platform.IS_MAC) {\n return MAC_DISPLAY.hasOwnProperty(key) ? MAC_DISPLAY[key] : key;\n }\n else {\n return WIN_DISPLAY.hasOwnProperty(key) ? WIN_DISPLAY[key] : key;\n }\n }\n Private.formatKey = formatKey;\n const MAC_DISPLAY = {\n Backspace: '⌫',\n Tab: '⇥',\n Enter: '⏎',\n Shift: '⇧',\n Ctrl: '⌃',\n Alt: '⌥',\n Escape: '⎋',\n PageUp: '⇞',\n PageDown: '⇟',\n End: '↘',\n Home: '↖',\n ArrowLeft: '←',\n ArrowUp: '↑',\n ArrowRight: '→',\n ArrowDown: '↓',\n Delete: '⌦',\n Cmd: '⌘'\n };\n const WIN_DISPLAY = {\n Escape: 'Esc',\n PageUp: 'Page Up',\n PageDown: 'Page Down',\n ArrowLeft: 'Left',\n ArrowUp: 'Up',\n ArrowRight: 'Right',\n ArrowDown: 'Down',\n Delete: 'Del'\n };\n /**\n * A singleton empty string function.\n */\n const emptyStringFunc = () => '';\n /**\n * A singleton `-1` number function\n */\n const negativeOneFunc = () => -1;\n /**\n * A singleton true boolean function.\n */\n const trueFunc = () => true;\n /**\n * A singleton false boolean function.\n */\n const falseFunc = () => false;\n /**\n * A singleton empty dataset function.\n */\n const emptyDatasetFunc = () => ({});\n /**\n * A singleton undefined function\n */\n const undefinedFunc = () => undefined;\n /**\n * Cast a value or command func to a command func.\n */\n function asFunc(value, dfault) {\n if (value === undefined) {\n return dfault;\n }\n if (typeof value === 'function') {\n return value;\n }\n return () => value;\n }\n /**\n * Validate the selector for an options object.\n *\n * This returns the validated selector, or throws if the selector is\n * invalid or contains commas.\n */\n function validateSelector(options) {\n if (options.selector.indexOf(',') !== -1) {\n throw new Error(`Selector cannot contain commas: ${options.selector}`);\n }\n if (!Selector.isValid(options.selector)) {\n throw new Error(`Invalid selector: ${options.selector}`);\n }\n return options.selector;\n }\n /**\n * Test whether a key binding sequence matches a key sequence.\n *\n * Returns a `SequenceMatch` value indicating the type of match.\n */\n function matchSequence(bindKeys, userKeys) {\n if (bindKeys.length < userKeys.length) {\n return 0 /* SequenceMatch.None */;\n }\n for (let i = 0, n = userKeys.length; i < n; ++i) {\n if (bindKeys[i] !== userKeys[i]) {\n return 0 /* SequenceMatch.None */;\n }\n }\n if (bindKeys.length > userKeys.length) {\n return 2 /* SequenceMatch.Partial */;\n }\n return 1 /* SequenceMatch.Exact */;\n }\n /**\n * Find the distance from the target node to the first matching node.\n *\n * This traverses the event path from `target` to `currentTarget` and\n * computes the distance from `target` to the first node which matches\n * the CSS selector. If no match is found, `-1` is returned.\n */\n function targetDistance(selector, event) {\n let targ = event.target;\n let curr = event.currentTarget;\n for (let dist = 0; targ !== null; targ = targ.parentElement, ++dist) {\n if (targ.hasAttribute('data-lm-suppress-shortcuts')) {\n return -1;\n }\n if (Selector.matches(targ, selector)) {\n return dist;\n }\n if (targ === curr) {\n return -1;\n }\n }\n return -1;\n }\n /**\n * Clone a keyboard event.\n */\n function cloneKeyboardEvent(event) {\n // A custom event is required because Chrome nulls out the\n // `keyCode` field in user-generated `KeyboardEvent` types.\n let clone = document.createEvent('Event');\n let bubbles = event.bubbles || true;\n let cancelable = event.cancelable || true;\n clone.initEvent(event.type || 'keydown', bubbles, cancelable);\n clone.key = event.key || '';\n clone.keyCode = event.keyCode || 0;\n clone.which = event.keyCode || 0;\n clone.ctrlKey = event.ctrlKey || false;\n clone.altKey = event.altKey || false;\n clone.shiftKey = event.shiftKey || false;\n clone.metaKey = event.metaKey || false;\n clone.view = event.view || window;\n return clone;\n }\n})(Private || (Private = {}));\n\nexport { CommandRegistry };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt } from '@lumino/algorithm';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module virtualdom\n */\n/**\n * A virtual node which represents plain text content.\n *\n * #### Notes\n * User code will not typically create a `VirtualText` node directly.\n * Instead, the `h()` function will be used to create an element tree.\n */\nclass VirtualText {\n /**\n * Construct a new virtual text node.\n *\n * @param content - The text content for the node.\n */\n constructor(content) {\n /**\n * The type of the node.\n *\n * This value can be used as a type guard for discriminating the\n * `VirtualNode` union type.\n */\n this.type = 'text';\n this.content = content;\n }\n}\n/**\n * A virtual node which represents an HTML element.\n *\n * #### Notes\n * User code will not typically create a `VirtualElement` node directly.\n * Instead, the `h()` function will be used to create an element tree.\n */\nclass VirtualElement {\n /**\n * Construct a new virtual element node.\n *\n * @param tag - The element tag name.\n *\n * @param attrs - The element attributes.\n *\n * @param children - The element children.\n *\n * @param renderer - An optional custom renderer for the element.\n */\n constructor(tag, attrs, children, renderer) {\n /**\n * The type of the node.\n *\n * This value can be used as a type guard for discriminating the\n * `VirtualNode` union type.\n */\n this.type = 'element';\n this.tag = tag;\n this.attrs = attrs;\n this.children = children;\n this.renderer = renderer;\n }\n}\n/**\n * DEPRECATED - use VirtualElement with a defined renderer param instead.\n * This class is provided as a backwards compatibility shim\n *\n * A \"pass thru\" virtual node whose children are managed by a render and an\n * unrender callback. The intent of this flavor of virtual node is to make\n * it easy to blend other kinds of virtualdom (eg React) into Phosphor's\n * virtualdom.\n *\n * #### Notes\n * User code will not typically create a `VirtualElementPass` node directly.\n * Instead, the `hpass()` function will be used to create an element tree.\n */\nclass VirtualElementPass extends VirtualElement {\n /**\n * DEPRECATED - use VirtualElement with a defined renderer param instead\n *\n * Construct a new virtual element pass thru node.\n *\n * @param tag - the tag of the parent element of this node. Once the parent\n * element is rendered, it will be passed as an argument to\n * renderer.render\n *\n * @param attrs - attributes that will assigned to the\n * parent element\n *\n * @param renderer - an object with render and unrender\n * functions, each of which should take a single argument of type\n * HTMLElement and return nothing. If null, the parent element\n * will be rendered barren without any children.\n */\n constructor(tag, attrs, renderer) {\n super(tag, attrs, [], renderer || undefined);\n }\n}\nfunction h(tag) {\n let attrs = {};\n let renderer;\n let children = [];\n for (let i = 1, n = arguments.length; i < n; ++i) {\n // eslint-disable-next-line prefer-rest-params\n let arg = arguments[i];\n if (typeof arg === 'string') {\n children.push(new VirtualText(arg));\n }\n else if (arg instanceof VirtualText) {\n children.push(arg);\n }\n else if (arg instanceof VirtualElement) {\n children.push(arg);\n }\n else if (arg instanceof Array) {\n extend(children, arg);\n }\n else if ((i === 1 || i === 2) && arg && typeof arg === 'object') {\n if ('render' in arg) {\n renderer = arg;\n }\n else {\n attrs = arg;\n }\n }\n }\n return new VirtualElement(tag, attrs, children, renderer);\n function extend(array, values) {\n for (let child of values) {\n if (typeof child === 'string') {\n array.push(new VirtualText(child));\n }\n else if (child instanceof VirtualText) {\n array.push(child);\n }\n else if (child instanceof VirtualElement) {\n array.push(child);\n }\n }\n }\n}\n/**\n * The namespace for the `h` function statics.\n */\n(function (h) {\n h.a = h.bind(undefined, 'a');\n h.abbr = h.bind(undefined, 'abbr');\n h.address = h.bind(undefined, 'address');\n h.area = h.bind(undefined, 'area');\n h.article = h.bind(undefined, 'article');\n h.aside = h.bind(undefined, 'aside');\n h.audio = h.bind(undefined, 'audio');\n h.b = h.bind(undefined, 'b');\n h.bdi = h.bind(undefined, 'bdi');\n h.bdo = h.bind(undefined, 'bdo');\n h.blockquote = h.bind(undefined, 'blockquote');\n h.br = h.bind(undefined, 'br');\n h.button = h.bind(undefined, 'button');\n h.canvas = h.bind(undefined, 'canvas');\n h.caption = h.bind(undefined, 'caption');\n h.cite = h.bind(undefined, 'cite');\n h.code = h.bind(undefined, 'code');\n h.col = h.bind(undefined, 'col');\n h.colgroup = h.bind(undefined, 'colgroup');\n h.data = h.bind(undefined, 'data');\n h.datalist = h.bind(undefined, 'datalist');\n h.dd = h.bind(undefined, 'dd');\n h.del = h.bind(undefined, 'del');\n h.dfn = h.bind(undefined, 'dfn');\n h.div = h.bind(undefined, 'div');\n h.dl = h.bind(undefined, 'dl');\n h.dt = h.bind(undefined, 'dt');\n h.em = h.bind(undefined, 'em');\n h.embed = h.bind(undefined, 'embed');\n h.fieldset = h.bind(undefined, 'fieldset');\n h.figcaption = h.bind(undefined, 'figcaption');\n h.figure = h.bind(undefined, 'figure');\n h.footer = h.bind(undefined, 'footer');\n h.form = h.bind(undefined, 'form');\n h.h1 = h.bind(undefined, 'h1');\n h.h2 = h.bind(undefined, 'h2');\n h.h3 = h.bind(undefined, 'h3');\n h.h4 = h.bind(undefined, 'h4');\n h.h5 = h.bind(undefined, 'h5');\n h.h6 = h.bind(undefined, 'h6');\n h.header = h.bind(undefined, 'header');\n h.hr = h.bind(undefined, 'hr');\n h.i = h.bind(undefined, 'i');\n h.iframe = h.bind(undefined, 'iframe');\n h.img = h.bind(undefined, 'img');\n h.input = h.bind(undefined, 'input');\n h.ins = h.bind(undefined, 'ins');\n h.kbd = h.bind(undefined, 'kbd');\n h.label = h.bind(undefined, 'label');\n h.legend = h.bind(undefined, 'legend');\n h.li = h.bind(undefined, 'li');\n h.main = h.bind(undefined, 'main');\n h.map = h.bind(undefined, 'map');\n h.mark = h.bind(undefined, 'mark');\n h.meter = h.bind(undefined, 'meter');\n h.nav = h.bind(undefined, 'nav');\n h.noscript = h.bind(undefined, 'noscript');\n h.object = h.bind(undefined, 'object');\n h.ol = h.bind(undefined, 'ol');\n h.optgroup = h.bind(undefined, 'optgroup');\n h.option = h.bind(undefined, 'option');\n h.output = h.bind(undefined, 'output');\n h.p = h.bind(undefined, 'p');\n h.param = h.bind(undefined, 'param');\n h.pre = h.bind(undefined, 'pre');\n h.progress = h.bind(undefined, 'progress');\n h.q = h.bind(undefined, 'q');\n h.rp = h.bind(undefined, 'rp');\n h.rt = h.bind(undefined, 'rt');\n h.ruby = h.bind(undefined, 'ruby');\n h.s = h.bind(undefined, 's');\n h.samp = h.bind(undefined, 'samp');\n h.section = h.bind(undefined, 'section');\n h.select = h.bind(undefined, 'select');\n h.small = h.bind(undefined, 'small');\n h.source = h.bind(undefined, 'source');\n h.span = h.bind(undefined, 'span');\n h.strong = h.bind(undefined, 'strong');\n h.sub = h.bind(undefined, 'sub');\n h.summary = h.bind(undefined, 'summary');\n h.sup = h.bind(undefined, 'sup');\n h.table = h.bind(undefined, 'table');\n h.tbody = h.bind(undefined, 'tbody');\n h.td = h.bind(undefined, 'td');\n h.textarea = h.bind(undefined, 'textarea');\n h.tfoot = h.bind(undefined, 'tfoot');\n h.th = h.bind(undefined, 'th');\n h.thead = h.bind(undefined, 'thead');\n h.time = h.bind(undefined, 'time');\n h.title = h.bind(undefined, 'title');\n h.tr = h.bind(undefined, 'tr');\n h.track = h.bind(undefined, 'track');\n h.u = h.bind(undefined, 'u');\n h.ul = h.bind(undefined, 'ul');\n h.var_ = h.bind(undefined, 'var');\n h.video = h.bind(undefined, 'video');\n h.wbr = h.bind(undefined, 'wbr');\n})(h || (h = {}));\nfunction hpass(tag) {\n let attrs = {};\n let renderer = null;\n if (arguments.length === 2) {\n // eslint-disable-next-line prefer-rest-params\n const arg = arguments[1];\n if ('render' in arg) {\n renderer = arg;\n }\n else {\n attrs = arg;\n }\n }\n else if (arguments.length === 3) {\n // eslint-disable-next-line prefer-rest-params\n attrs = arguments[1];\n // eslint-disable-next-line prefer-rest-params\n renderer = arguments[2];\n }\n else if (arguments.length > 3) {\n throw new Error('hpass() should be called with 1, 2, or 3 arguments');\n }\n return new VirtualElementPass(tag, attrs, renderer);\n}\n/**\n * The namespace for the virtual DOM rendering functions.\n */\nvar VirtualDOM;\n(function (VirtualDOM) {\n function realize(node) {\n return Private.createDOMNode(node);\n }\n VirtualDOM.realize = realize;\n /**\n * Render virtual DOM content into a host element.\n *\n * @param content - The virtual DOM content to render.\n *\n * @param host - The host element for the rendered content.\n *\n * #### Notes\n * This renders the delta from the previous rendering. It assumes that\n * the content of the host element is not manipulated by external code.\n *\n * Providing `null` content will clear the rendering.\n *\n * Externally modifying the provided content or the host element will\n * result in undefined rendering behavior.\n */\n function render(content, host) {\n let oldContent = Private.hostMap.get(host) || [];\n let newContent = Private.asContentArray(content);\n Private.hostMap.set(host, newContent);\n Private.updateContent(host, oldContent, newContent);\n }\n VirtualDOM.render = render;\n})(VirtualDOM || (VirtualDOM = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A weak mapping of host element to virtual DOM content.\n */\n Private.hostMap = new WeakMap();\n /**\n * Cast a content value to a content array.\n */\n function asContentArray(value) {\n if (!value) {\n return [];\n }\n if (value instanceof Array) {\n return value;\n }\n return [value];\n }\n Private.asContentArray = asContentArray;\n function createDOMNode(node) {\n // eslint-disable-next-line prefer-rest-params\n let host = arguments[1] || null;\n // eslint-disable-next-line prefer-rest-params\n const before = arguments[2] || null;\n if (host) {\n host.insertBefore(createDOMNode(node), before);\n }\n else {\n // Create a text node for a virtual text node.\n if (node.type === 'text') {\n return document.createTextNode(node.content);\n }\n // Create the HTML element with the specified tag.\n host = document.createElement(node.tag);\n // Add the attributes for the new element.\n addAttrs(host, node.attrs);\n if (node.renderer) {\n node.renderer.render(host, {\n attrs: node.attrs,\n children: node.children\n });\n return host;\n }\n // Recursively populate the element with child content.\n for (let i = 0, n = node.children.length; i < n; ++i) {\n createDOMNode(node.children[i], host);\n }\n }\n return host;\n }\n Private.createDOMNode = createDOMNode;\n /**\n * Update a host element with the delta of the virtual content.\n *\n * This is the core \"diff\" algorithm. There is no explicit \"patch\"\n * phase. The host is patched at each step as the diff progresses.\n */\n function updateContent(host, oldContent, newContent) {\n // Bail early if the content is identical.\n if (oldContent === newContent) {\n return;\n }\n // Collect the old keyed elems into a mapping.\n let oldKeyed = collectKeys(host, oldContent);\n // Create a copy of the old content which can be modified in-place.\n let oldCopy = oldContent.slice();\n // Update the host with the new content. The diff always proceeds\n // forward and never modifies a previously visited index. The old\n // copy array is modified in-place to reflect the changes made to\n // the host children. This causes the stale nodes to be pushed to\n // the end of the host node and removed at the end of the loop.\n let currElem = host.firstChild;\n let newCount = newContent.length;\n for (let i = 0; i < newCount; ++i) {\n // If the old content is exhausted, create a new node.\n if (i >= oldCopy.length) {\n createDOMNode(newContent[i], host);\n continue;\n }\n // Lookup the old and new virtual nodes.\n let oldVNode = oldCopy[i];\n let newVNode = newContent[i];\n // If both elements are identical, there is nothing to do.\n if (oldVNode === newVNode) {\n currElem = currElem.nextSibling;\n continue;\n }\n // Handle the simplest case of in-place text update first.\n if (oldVNode.type === 'text' && newVNode.type === 'text') {\n // Avoid spurious updates for performance.\n if (currElem.textContent !== newVNode.content) {\n currElem.textContent = newVNode.content;\n }\n currElem = currElem.nextSibling;\n continue;\n }\n // If the old or new node is a text node, the other node is now\n // known to be an element node, so create and insert a new node.\n if (oldVNode.type === 'text' || newVNode.type === 'text') {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // If the old XOR new node has a custom renderer,\n // create and insert a new node.\n if (!oldVNode.renderer != !newVNode.renderer) {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // At this point, both nodes are known to be element nodes.\n // If the new elem is keyed, move an old keyed elem to the proper\n // location before proceeding with the diff. The search can start\n // at the current index, since the unmatched old keyed elems are\n // pushed forward in the old copy array.\n let newKey = newVNode.attrs.key;\n if (newKey && newKey in oldKeyed) {\n let pair = oldKeyed[newKey];\n if (pair.vNode !== oldVNode) {\n ArrayExt.move(oldCopy, oldCopy.indexOf(pair.vNode, i + 1), i);\n host.insertBefore(pair.element, currElem);\n oldVNode = pair.vNode;\n currElem = pair.element;\n }\n }\n // If both elements are identical, there is nothing to do.\n if (oldVNode === newVNode) {\n currElem = currElem.nextSibling;\n continue;\n }\n // If the old elem is keyed and does not match the new elem key,\n // create a new node. This is necessary since the old keyed elem\n // may be matched at a later point in the diff.\n let oldKey = oldVNode.attrs.key;\n if (oldKey && oldKey !== newKey) {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // If the tags are different, create a new node.\n if (oldVNode.tag !== newVNode.tag) {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // At this point, the element can be updated in-place.\n // Update the element attributes.\n updateAttrs(currElem, oldVNode.attrs, newVNode.attrs);\n // Update the element content.\n if (newVNode.renderer) {\n newVNode.renderer.render(currElem, {\n attrs: newVNode.attrs,\n children: newVNode.children\n });\n }\n else {\n updateContent(currElem, oldVNode.children, newVNode.children);\n }\n // Step to the next sibling element.\n currElem = currElem.nextSibling;\n }\n // Cleanup stale DOM\n removeContent(host, oldCopy, newCount, true);\n }\n Private.updateContent = updateContent;\n /**\n * Handle cleanup of stale vdom and its associated DOM. The host node is\n * traversed recursively (in depth-first order), and any explicit cleanup\n * required by a child node is carried out when it is visited (eg if a node\n * has a custom renderer, the renderer.unrender function will be called).\n * Once the subtree beneath each child of host has been completely visited,\n * that child will be removed via a call to host.removeChild.\n */\n function removeContent(host, oldContent, newCount, _sentinel) {\n // Dispose of the old nodes pushed to the end of the host.\n for (let i = oldContent.length - 1; i >= newCount; --i) {\n const oldNode = oldContent[i];\n const child = (_sentinel ? host.lastChild : host.childNodes[i]);\n // recursively clean up host children\n if (oldNode.type === 'text') ;\n else if (oldNode.renderer && oldNode.renderer.unrender) {\n oldNode.renderer.unrender(child, {\n attrs: oldNode.attrs,\n children: oldNode.children\n });\n }\n else {\n removeContent(child, oldNode.children, 0, false);\n }\n if (_sentinel) {\n host.removeChild(child);\n }\n }\n }\n /**\n * A set of special-cased attribute names.\n */\n const specialAttrs = {\n key: true,\n className: true,\n htmlFor: true,\n dataset: true,\n style: true\n };\n /**\n * Add element attributes to a newly created HTML element.\n */\n function addAttrs(element, attrs) {\n // Add the inline event listeners and node attributes.\n for (let name in attrs) {\n if (name in specialAttrs) {\n continue;\n }\n if (name.substr(0, 2) === 'on') {\n element[name] = attrs[name];\n }\n else {\n element.setAttribute(name, attrs[name]);\n }\n }\n // Add the element `class` attribute.\n if (attrs.className !== undefined) {\n element.setAttribute('class', attrs.className);\n }\n // Add the element `for` attribute.\n if (attrs.htmlFor !== undefined) {\n element.setAttribute('for', attrs.htmlFor);\n }\n // Add the dataset values.\n if (attrs.dataset) {\n addDataset(element, attrs.dataset);\n }\n // Add the inline styles.\n if (attrs.style) {\n addStyle(element, attrs.style);\n }\n }\n /**\n * Update the element attributes of an HTML element.\n */\n function updateAttrs(element, oldAttrs, newAttrs) {\n // Do nothing if the attrs are the same object.\n if (oldAttrs === newAttrs) {\n return;\n }\n // Setup the strongly typed loop variable.\n let name;\n // Remove attributes and listeners which no longer exist.\n for (name in oldAttrs) {\n if (name in specialAttrs || name in newAttrs) {\n continue;\n }\n if (name.substr(0, 2) === 'on') {\n element[name] = null;\n }\n else {\n element.removeAttribute(name);\n }\n }\n // Add and update new and existing attributes and listeners.\n for (name in newAttrs) {\n if (name in specialAttrs || oldAttrs[name] === newAttrs[name]) {\n continue;\n }\n if (name.substr(0, 2) === 'on') {\n element[name] = newAttrs[name];\n }\n else {\n element.setAttribute(name, newAttrs[name]);\n }\n }\n // Update the element `class` attribute.\n if (oldAttrs.className !== newAttrs.className) {\n if (newAttrs.className !== undefined) {\n element.setAttribute('class', newAttrs.className);\n }\n else {\n element.removeAttribute('class');\n }\n }\n // Add the element `for` attribute.\n if (oldAttrs.htmlFor !== newAttrs.htmlFor) {\n if (newAttrs.htmlFor !== undefined) {\n element.setAttribute('for', newAttrs.htmlFor);\n }\n else {\n element.removeAttribute('for');\n }\n }\n // Update the dataset values.\n if (oldAttrs.dataset !== newAttrs.dataset) {\n updateDataset(element, oldAttrs.dataset || {}, newAttrs.dataset || {});\n }\n // Update the inline styles.\n if (oldAttrs.style !== newAttrs.style) {\n updateStyle(element, oldAttrs.style || {}, newAttrs.style || {});\n }\n }\n /**\n * Add dataset values to a newly created HTML element.\n */\n function addDataset(element, dataset) {\n for (let name in dataset) {\n element.setAttribute(`data-${name}`, dataset[name]);\n }\n }\n /**\n * Update the dataset values of an HTML element.\n */\n function updateDataset(element, oldDataset, newDataset) {\n for (let name in oldDataset) {\n if (!(name in newDataset)) {\n element.removeAttribute(`data-${name}`);\n }\n }\n for (let name in newDataset) {\n if (oldDataset[name] !== newDataset[name]) {\n element.setAttribute(`data-${name}`, newDataset[name]);\n }\n }\n }\n /**\n * Add inline style values to a newly created HTML element.\n */\n function addStyle(element, style) {\n let elemStyle = element.style;\n let name;\n for (name in style) {\n elemStyle[name] = style[name];\n }\n }\n /**\n * Update the inline style values of an HTML element.\n */\n function updateStyle(element, oldStyle, newStyle) {\n let elemStyle = element.style;\n let name;\n for (name in oldStyle) {\n if (!(name in newStyle)) {\n elemStyle[name] = '';\n }\n }\n for (name in newStyle) {\n if (oldStyle[name] !== newStyle[name]) {\n elemStyle[name] = newStyle[name];\n }\n }\n }\n /**\n * Collect a mapping of keyed elements for the host content.\n */\n function collectKeys(host, content) {\n let node = host.firstChild;\n let keyMap = Object.create(null);\n for (let vNode of content) {\n if (vNode.type === 'element' && vNode.attrs.key) {\n keyMap[vNode.attrs.key] = { vNode, element: node };\n }\n node = node.nextSibling;\n }\n return keyMap;\n }\n})(Private || (Private = {}));\n\nexport { VirtualDOM, VirtualElement, VirtualElementPass, VirtualText, h, hpass };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt, StringExt, empty, find, max } from '@lumino/algorithm';\nimport { UUID, JSONExt, MimeData } from '@lumino/coreutils';\nimport { ElementExt, Selector, Platform } from '@lumino/domutils';\nimport { Message, ConflatableMessage, MessageLoop } from '@lumino/messaging';\nimport { AttachedProperty } from '@lumino/properties';\nimport { Signal } from '@lumino/signaling';\nimport { Drag } from '@lumino/dragdrop';\nimport { CommandRegistry } from '@lumino/commands';\nimport { VirtualDOM, h } from '@lumino/virtualdom';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport { getKeyboardLayout } from '@lumino/keyboard';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A sizer object for use with the box engine layout functions.\n *\n * #### Notes\n * A box sizer holds the geometry information for an object along an\n * arbitrary layout orientation.\n *\n * For best performance, this class should be treated as a raw data\n * struct. It should not typically be subclassed.\n */\nclass BoxSizer {\n constructor() {\n /**\n * The preferred size for the sizer.\n *\n * #### Notes\n * The sizer will be given this initial size subject to its size\n * bounds. The sizer will not deviate from this size unless such\n * deviation is required to fit into the available layout space.\n *\n * There is no limit to this value, but it will be clamped to the\n * bounds defined by {@link minSize} and {@link maxSize}.\n *\n * The default value is `0`.\n */\n this.sizeHint = 0;\n /**\n * The minimum size of the sizer.\n *\n * #### Notes\n * The sizer will never be sized less than this value, even if\n * it means the sizer will overflow the available layout space.\n *\n * It is assumed that this value lies in the range `[0, Infinity)`\n * and that it is `<=` to {@link maxSize}. Failure to adhere to this\n * constraint will yield undefined results.\n *\n * The default value is `0`.\n */\n this.minSize = 0;\n /**\n * The maximum size of the sizer.\n *\n * #### Notes\n * The sizer will never be sized greater than this value, even if\n * it means the sizer will underflow the available layout space.\n *\n * It is assumed that this value lies in the range `[0, Infinity]`\n * and that it is `>=` to {@link minSize}. Failure to adhere to this\n * constraint will yield undefined results.\n *\n * The default value is `Infinity`.\n */\n this.maxSize = Infinity;\n /**\n * The stretch factor for the sizer.\n *\n * #### Notes\n * This controls how much the sizer stretches relative to its sibling\n * sizers when layout space is distributed. A stretch factor of zero\n * is special and will cause the sizer to only be resized after all\n * other sizers with a stretch factor greater than zero have been\n * resized to their limits.\n *\n * It is assumed that this value is an integer that lies in the range\n * `[0, Infinity)`. Failure to adhere to this constraint will yield\n * undefined results.\n *\n * The default value is `1`.\n */\n this.stretch = 1;\n /**\n * The computed size of the sizer.\n *\n * #### Notes\n * This value is the output of a call to {@link BoxEngine.calc}. It represents\n * the computed size for the object along the layout orientation,\n * and will always lie in the range `[minSize, maxSize]`.\n *\n * This value is output only.\n *\n * Changing this value will have no effect.\n */\n this.size = 0;\n /**\n * An internal storage property for the layout algorithm.\n *\n * #### Notes\n * This value is used as temporary storage by the layout algorithm.\n *\n * Changing this value will have no effect.\n */\n this.done = false;\n }\n}\n/**\n * The namespace for the box engine layout functions.\n */\nvar BoxEngine;\n(function (BoxEngine) {\n /**\n * Calculate the optimal layout sizes for a sequence of box sizers.\n *\n * This distributes the available layout space among the box sizers\n * according to the following algorithm:\n *\n * 1. Initialize the sizers's size to its size hint and compute the\n * sums for each of size hint, min size, and max size.\n *\n * 2. If the total size hint equals the available space, return.\n *\n * 3. If the available space is less than the total min size, set all\n * sizers to their min size and return.\n *\n * 4. If the available space is greater than the total max size, set\n * all sizers to their max size and return.\n *\n * 5. If the layout space is less than the total size hint, distribute\n * the negative delta as follows:\n *\n * a. Shrink each sizer with a stretch factor greater than zero by\n * an amount proportional to the negative space and the sum of\n * stretch factors. If the sizer reaches its min size, remove\n * it and its stretch factor from the computation.\n *\n * b. If after adjusting all stretch sizers there remains negative\n * space, distribute the space equally among the sizers with a\n * stretch factor of zero. If a sizer reaches its min size,\n * remove it from the computation.\n *\n * 6. If the layout space is greater than the total size hint,\n * distribute the positive delta as follows:\n *\n * a. Expand each sizer with a stretch factor greater than zero by\n * an amount proportional to the postive space and the sum of\n * stretch factors. If the sizer reaches its max size, remove\n * it and its stretch factor from the computation.\n *\n * b. If after adjusting all stretch sizers there remains positive\n * space, distribute the space equally among the sizers with a\n * stretch factor of zero. If a sizer reaches its max size,\n * remove it from the computation.\n *\n * 7. return\n *\n * @param sizers - The sizers for a particular layout line.\n *\n * @param space - The available layout space for the sizers.\n *\n * @returns The delta between the provided available space and the\n * actual consumed space. This value will be zero if the sizers\n * can be adjusted to fit, negative if the available space is too\n * small, and positive if the available space is too large.\n *\n * #### Notes\n * The {@link BoxSizer.size} of each sizer is updated with the computed size.\n *\n * This function can be called at any time to recompute the layout for\n * an existing sequence of sizers. The previously computed results will\n * have no effect on the new output. It is therefore not necessary to\n * create new sizer objects on each resize event.\n */\n function calc(sizers, space) {\n // Bail early if there is nothing to do.\n let count = sizers.length;\n if (count === 0) {\n return space;\n }\n // Setup the size and stretch counters.\n let totalMin = 0;\n let totalMax = 0;\n let totalSize = 0;\n let totalStretch = 0;\n let stretchCount = 0;\n // Setup the sizers and compute the totals.\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n let min = sizer.minSize;\n let max = sizer.maxSize;\n let hint = sizer.sizeHint;\n sizer.done = false;\n sizer.size = Math.max(min, Math.min(hint, max));\n totalSize += sizer.size;\n totalMin += min;\n totalMax += max;\n if (sizer.stretch > 0) {\n totalStretch += sizer.stretch;\n stretchCount++;\n }\n }\n // If the space is equal to the total size, return early.\n if (space === totalSize) {\n return 0;\n }\n // If the space is less than the total min, minimize each sizer.\n if (space <= totalMin) {\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n sizer.size = sizer.minSize;\n }\n return space - totalMin;\n }\n // If the space is greater than the total max, maximize each sizer.\n if (space >= totalMax) {\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n sizer.size = sizer.maxSize;\n }\n return space - totalMax;\n }\n // The loops below perform sub-pixel precision sizing. A near zero\n // value is used for compares instead of zero to ensure that the\n // loop terminates when the subdivided space is reasonably small.\n let nearZero = 0.01;\n // A counter which is decremented each time a sizer is resized to\n // its limit. This ensures the loops terminate even if there is\n // space remaining to distribute.\n let notDoneCount = count;\n // Distribute negative delta space.\n if (space < totalSize) {\n // Shrink each stretchable sizer by an amount proportional to its\n // stretch factor. If a sizer reaches its min size it's marked as\n // done. The loop progresses in phases where each sizer is given\n // a chance to consume its fair share for the pass, regardless of\n // whether a sizer before it reached its limit. This continues\n // until the stretchable sizers or the free space is exhausted.\n let freeSpace = totalSize - space;\n while (stretchCount > 0 && freeSpace > nearZero) {\n let distSpace = freeSpace;\n let distStretch = totalStretch;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done || sizer.stretch === 0) {\n continue;\n }\n let amt = (sizer.stretch * distSpace) / distStretch;\n if (sizer.size - amt <= sizer.minSize) {\n freeSpace -= sizer.size - sizer.minSize;\n totalStretch -= sizer.stretch;\n sizer.size = sizer.minSize;\n sizer.done = true;\n notDoneCount--;\n stretchCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size -= amt;\n }\n }\n }\n // Distribute any remaining space evenly among the non-stretchable\n // sizers. This progresses in phases in the same manner as above.\n while (notDoneCount > 0 && freeSpace > nearZero) {\n let amt = freeSpace / notDoneCount;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done) {\n continue;\n }\n if (sizer.size - amt <= sizer.minSize) {\n freeSpace -= sizer.size - sizer.minSize;\n sizer.size = sizer.minSize;\n sizer.done = true;\n notDoneCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size -= amt;\n }\n }\n }\n }\n // Distribute positive delta space.\n else {\n // Expand each stretchable sizer by an amount proportional to its\n // stretch factor. If a sizer reaches its max size it's marked as\n // done. The loop progresses in phases where each sizer is given\n // a chance to consume its fair share for the pass, regardless of\n // whether a sizer before it reached its limit. This continues\n // until the stretchable sizers or the free space is exhausted.\n let freeSpace = space - totalSize;\n while (stretchCount > 0 && freeSpace > nearZero) {\n let distSpace = freeSpace;\n let distStretch = totalStretch;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done || sizer.stretch === 0) {\n continue;\n }\n let amt = (sizer.stretch * distSpace) / distStretch;\n if (sizer.size + amt >= sizer.maxSize) {\n freeSpace -= sizer.maxSize - sizer.size;\n totalStretch -= sizer.stretch;\n sizer.size = sizer.maxSize;\n sizer.done = true;\n notDoneCount--;\n stretchCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size += amt;\n }\n }\n }\n // Distribute any remaining space evenly among the non-stretchable\n // sizers. This progresses in phases in the same manner as above.\n while (notDoneCount > 0 && freeSpace > nearZero) {\n let amt = freeSpace / notDoneCount;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done) {\n continue;\n }\n if (sizer.size + amt >= sizer.maxSize) {\n freeSpace -= sizer.maxSize - sizer.size;\n sizer.size = sizer.maxSize;\n sizer.done = true;\n notDoneCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size += amt;\n }\n }\n }\n }\n // Indicate that the consumed space equals the available space.\n return 0;\n }\n BoxEngine.calc = calc;\n /**\n * Adjust a sizer by a delta and update its neighbors accordingly.\n *\n * @param sizers - The sizers which should be adjusted.\n *\n * @param index - The index of the sizer to grow.\n *\n * @param delta - The amount to adjust the sizer, positive or negative.\n *\n * #### Notes\n * This will adjust the indicated sizer by the specified amount, along\n * with the sizes of the appropriate neighbors, subject to the limits\n * specified by each of the sizers.\n *\n * This is useful when implementing box layouts where the boundaries\n * between the sizers are interactively adjustable by the user.\n */\n function adjust(sizers, index, delta) {\n // Bail early when there is nothing to do.\n if (sizers.length === 0 || delta === 0) {\n return;\n }\n // Dispatch to the proper implementation.\n if (delta > 0) {\n growSizer(sizers, index, delta);\n }\n else {\n shrinkSizer(sizers, index, -delta);\n }\n }\n BoxEngine.adjust = adjust;\n /**\n * Grow a sizer by a positive delta and adjust neighbors.\n */\n function growSizer(sizers, index, delta) {\n // Compute how much the items to the left can expand.\n let growLimit = 0;\n for (let i = 0; i <= index; ++i) {\n let sizer = sizers[i];\n growLimit += sizer.maxSize - sizer.size;\n }\n // Compute how much the items to the right can shrink.\n let shrinkLimit = 0;\n for (let i = index + 1, n = sizers.length; i < n; ++i) {\n let sizer = sizers[i];\n shrinkLimit += sizer.size - sizer.minSize;\n }\n // Clamp the delta adjustment to the limits.\n delta = Math.min(delta, growLimit, shrinkLimit);\n // Grow the sizers to the left by the delta.\n let grow = delta;\n for (let i = index; i >= 0 && grow > 0; --i) {\n let sizer = sizers[i];\n let limit = sizer.maxSize - sizer.size;\n if (limit >= grow) {\n sizer.sizeHint = sizer.size + grow;\n grow = 0;\n }\n else {\n sizer.sizeHint = sizer.size + limit;\n grow -= limit;\n }\n }\n // Shrink the sizers to the right by the delta.\n let shrink = delta;\n for (let i = index + 1, n = sizers.length; i < n && shrink > 0; ++i) {\n let sizer = sizers[i];\n let limit = sizer.size - sizer.minSize;\n if (limit >= shrink) {\n sizer.sizeHint = sizer.size - shrink;\n shrink = 0;\n }\n else {\n sizer.sizeHint = sizer.size - limit;\n shrink -= limit;\n }\n }\n }\n /**\n * Shrink a sizer by a positive delta and adjust neighbors.\n */\n function shrinkSizer(sizers, index, delta) {\n // Compute how much the items to the right can expand.\n let growLimit = 0;\n for (let i = index + 1, n = sizers.length; i < n; ++i) {\n let sizer = sizers[i];\n growLimit += sizer.maxSize - sizer.size;\n }\n // Compute how much the items to the left can shrink.\n let shrinkLimit = 0;\n for (let i = 0; i <= index; ++i) {\n let sizer = sizers[i];\n shrinkLimit += sizer.size - sizer.minSize;\n }\n // Clamp the delta adjustment to the limits.\n delta = Math.min(delta, growLimit, shrinkLimit);\n // Grow the sizers to the right by the delta.\n let grow = delta;\n for (let i = index + 1, n = sizers.length; i < n && grow > 0; ++i) {\n let sizer = sizers[i];\n let limit = sizer.maxSize - sizer.size;\n if (limit >= grow) {\n sizer.sizeHint = sizer.size + grow;\n grow = 0;\n }\n else {\n sizer.sizeHint = sizer.size + limit;\n grow -= limit;\n }\n }\n // Shrink the sizers to the left by the delta.\n let shrink = delta;\n for (let i = index; i >= 0 && shrink > 0; --i) {\n let sizer = sizers[i];\n let limit = sizer.size - sizer.minSize;\n if (limit >= shrink) {\n sizer.sizeHint = sizer.size - shrink;\n shrink = 0;\n }\n else {\n sizer.sizeHint = sizer.size - limit;\n shrink -= limit;\n }\n }\n }\n})(BoxEngine || (BoxEngine = {}));\n\n/**\n * An object which holds data related to an object's title.\n *\n * #### Notes\n * A title object is intended to hold the data necessary to display a\n * header for a particular object. A common example is the `TabPanel`,\n * which uses the widget title to populate the tab for a child widget.\n *\n * It is the responsibility of the owner to call the title disposal.\n */\nclass Title {\n /**\n * Construct a new title.\n *\n * @param options - The options for initializing the title.\n */\n constructor(options) {\n this._label = '';\n this._caption = '';\n this._mnemonic = -1;\n this._icon = undefined;\n this._iconClass = '';\n this._iconLabel = '';\n this._className = '';\n this._closable = false;\n this._changed = new Signal(this);\n this._isDisposed = false;\n this.owner = options.owner;\n if (options.label !== undefined) {\n this._label = options.label;\n }\n if (options.mnemonic !== undefined) {\n this._mnemonic = options.mnemonic;\n }\n if (options.icon !== undefined) {\n this._icon = options.icon;\n }\n if (options.iconClass !== undefined) {\n this._iconClass = options.iconClass;\n }\n if (options.iconLabel !== undefined) {\n this._iconLabel = options.iconLabel;\n }\n if (options.caption !== undefined) {\n this._caption = options.caption;\n }\n if (options.className !== undefined) {\n this._className = options.className;\n }\n if (options.closable !== undefined) {\n this._closable = options.closable;\n }\n this._dataset = options.dataset || {};\n }\n /**\n * A signal emitted when the state of the title changes.\n */\n get changed() {\n return this._changed;\n }\n /**\n * Get the label for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get label() {\n return this._label;\n }\n /**\n * Set the label for the title.\n */\n set label(value) {\n if (this._label === value) {\n return;\n }\n this._label = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the mnemonic index for the title.\n *\n * #### Notes\n * The default value is `-1`.\n */\n get mnemonic() {\n return this._mnemonic;\n }\n /**\n * Set the mnemonic index for the title.\n */\n set mnemonic(value) {\n if (this._mnemonic === value) {\n return;\n }\n this._mnemonic = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the icon renderer for the title.\n *\n * #### Notes\n * The default value is undefined.\n */\n get icon() {\n return this._icon;\n }\n /**\n * Set the icon renderer for the title.\n *\n * #### Notes\n * A renderer is an object that supplies a render and unrender function.\n */\n set icon(value) {\n if (this._icon === value) {\n return;\n }\n this._icon = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the icon class name for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get iconClass() {\n return this._iconClass;\n }\n /**\n * Set the icon class name for the title.\n *\n * #### Notes\n * Multiple class names can be separated with whitespace.\n */\n set iconClass(value) {\n if (this._iconClass === value) {\n return;\n }\n this._iconClass = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the icon label for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get iconLabel() {\n return this._iconLabel;\n }\n /**\n * Set the icon label for the title.\n *\n * #### Notes\n * Multiple class names can be separated with whitespace.\n */\n set iconLabel(value) {\n if (this._iconLabel === value) {\n return;\n }\n this._iconLabel = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the caption for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get caption() {\n return this._caption;\n }\n /**\n * Set the caption for the title.\n */\n set caption(value) {\n if (this._caption === value) {\n return;\n }\n this._caption = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the extra class name for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get className() {\n return this._className;\n }\n /**\n * Set the extra class name for the title.\n *\n * #### Notes\n * Multiple class names can be separated with whitespace.\n */\n set className(value) {\n if (this._className === value) {\n return;\n }\n this._className = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the closable state for the title.\n *\n * #### Notes\n * The default value is `false`.\n */\n get closable() {\n return this._closable;\n }\n /**\n * Set the closable state for the title.\n *\n * #### Notes\n * This controls the presence of a close icon when applicable.\n */\n set closable(value) {\n if (this._closable === value) {\n return;\n }\n this._closable = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the dataset for the title.\n *\n * #### Notes\n * The default value is an empty dataset.\n */\n get dataset() {\n return this._dataset;\n }\n /**\n * Set the dataset for the title.\n *\n * #### Notes\n * This controls the data attributes when applicable.\n */\n set dataset(value) {\n if (this._dataset === value) {\n return;\n }\n this._dataset = value;\n this._changed.emit(undefined);\n }\n /**\n * Test whether the title has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the title.\n *\n * #### Notes\n * It is the responsibility of the owner to call the title disposal.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n}\n\n/**\n * The base class of the lumino widget hierarchy.\n *\n * #### Notes\n * This class will typically be subclassed in order to create a useful\n * widget. However, it can be used directly to host externally created\n * content.\n */\nclass Widget {\n /**\n * Construct a new widget.\n *\n * @param options - The options for initializing the widget.\n */\n constructor(options = {}) {\n this._flags = 0;\n this._layout = null;\n this._parent = null;\n this._disposed = new Signal(this);\n this._hiddenMode = Widget.HiddenMode.Display;\n this.node = Private$j.createNode(options);\n this.addClass('lm-Widget');\n }\n /**\n * Dispose of the widget and its descendant widgets.\n *\n * #### Notes\n * It is unsafe to use the widget after it has been disposed.\n *\n * All calls made to this method after the first are a no-op.\n */\n dispose() {\n // Do nothing if the widget is already disposed.\n if (this.isDisposed) {\n return;\n }\n // Set the disposed flag and emit the disposed signal.\n this.setFlag(Widget.Flag.IsDisposed);\n this._disposed.emit(undefined);\n // Remove or detach the widget if necessary.\n if (this.parent) {\n this.parent = null;\n }\n else if (this.isAttached) {\n Widget.detach(this);\n }\n // Dispose of the widget layout.\n if (this._layout) {\n this._layout.dispose();\n this._layout = null;\n }\n // Dispose the title\n this.title.dispose();\n // Clear the extra data associated with the widget.\n Signal.clearData(this);\n MessageLoop.clearData(this);\n AttachedProperty.clearData(this);\n }\n /**\n * A signal emitted when the widget is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Test whether the widget has been disposed.\n */\n get isDisposed() {\n return this.testFlag(Widget.Flag.IsDisposed);\n }\n /**\n * Test whether the widget's node is attached to the DOM.\n */\n get isAttached() {\n return this.testFlag(Widget.Flag.IsAttached);\n }\n /**\n * Test whether the widget is explicitly hidden.\n */\n get isHidden() {\n return this.testFlag(Widget.Flag.IsHidden);\n }\n /**\n * Test whether the widget is visible.\n *\n * #### Notes\n * A widget is visible when it is attached to the DOM, is not\n * explicitly hidden, and has no explicitly hidden ancestors.\n */\n get isVisible() {\n return this.testFlag(Widget.Flag.IsVisible);\n }\n /**\n * The title object for the widget.\n *\n * #### Notes\n * The title object is used by some container widgets when displaying\n * the widget alongside some title, such as a tab panel or side bar.\n *\n * Since not all widgets will use the title, it is created on demand.\n *\n * The `owner` property of the title is set to this widget.\n */\n get title() {\n return Private$j.titleProperty.get(this);\n }\n /**\n * Get the id of the widget's DOM node.\n */\n get id() {\n return this.node.id;\n }\n /**\n * Set the id of the widget's DOM node.\n */\n set id(value) {\n this.node.id = value;\n }\n /**\n * The dataset for the widget's DOM node.\n */\n get dataset() {\n return this.node.dataset;\n }\n /**\n * Get the method for hiding the widget.\n */\n get hiddenMode() {\n return this._hiddenMode;\n }\n /**\n * Set the method for hiding the widget.\n */\n set hiddenMode(value) {\n if (this._hiddenMode === value) {\n return;\n }\n if (this.isHidden) {\n // Reset styles set by previous mode.\n this._toggleHidden(false);\n }\n if (value == Widget.HiddenMode.Scale) {\n this.node.style.willChange = 'transform';\n }\n else {\n this.node.style.willChange = 'auto';\n }\n this._hiddenMode = value;\n if (this.isHidden) {\n // Set styles for new mode.\n this._toggleHidden(true);\n }\n }\n /**\n * Get the parent of the widget.\n */\n get parent() {\n return this._parent;\n }\n /**\n * Set the parent of the widget.\n *\n * #### Notes\n * Children are typically added to a widget by using a layout, which\n * means user code will not normally set the parent widget directly.\n *\n * The widget will be automatically removed from its old parent.\n *\n * This is a no-op if there is no effective parent change.\n */\n set parent(value) {\n if (this._parent === value) {\n return;\n }\n if (value && this.contains(value)) {\n throw new Error('Invalid parent widget.');\n }\n if (this._parent && !this._parent.isDisposed) {\n let msg = new Widget.ChildMessage('child-removed', this);\n MessageLoop.sendMessage(this._parent, msg);\n }\n this._parent = value;\n if (this._parent && !this._parent.isDisposed) {\n let msg = new Widget.ChildMessage('child-added', this);\n MessageLoop.sendMessage(this._parent, msg);\n }\n if (!this.isDisposed) {\n MessageLoop.sendMessage(this, Widget.Msg.ParentChanged);\n }\n }\n /**\n * Get the layout for the widget.\n */\n get layout() {\n return this._layout;\n }\n /**\n * Set the layout for the widget.\n *\n * #### Notes\n * The layout is single-use only. It cannot be changed after the\n * first assignment.\n *\n * The layout is disposed automatically when the widget is disposed.\n */\n set layout(value) {\n if (this._layout === value) {\n return;\n }\n if (this.testFlag(Widget.Flag.DisallowLayout)) {\n throw new Error('Cannot set widget layout.');\n }\n if (this._layout) {\n throw new Error('Cannot change widget layout.');\n }\n if (value.parent) {\n throw new Error('Cannot change layout parent.');\n }\n this._layout = value;\n value.parent = this;\n }\n /**\n * Create an iterator over the widget's children.\n *\n * @returns A new iterator over the children of the widget.\n *\n * #### Notes\n * The widget must have a populated layout in order to have children.\n *\n * If a layout is not installed, the returned iterator will be empty.\n */\n *children() {\n if (this._layout) {\n yield* this._layout;\n }\n }\n /**\n * Test whether a widget is a descendant of this widget.\n *\n * @param widget - The descendant widget of interest.\n *\n * @returns `true` if the widget is a descendant, `false` otherwise.\n */\n contains(widget) {\n for (let value = widget; value; value = value._parent) {\n if (value === this) {\n return true;\n }\n }\n return false;\n }\n /**\n * Test whether the widget's DOM node has the given class name.\n *\n * @param name - The class name of interest.\n *\n * @returns `true` if the node has the class, `false` otherwise.\n */\n hasClass(name) {\n return this.node.classList.contains(name);\n }\n /**\n * Add a class name to the widget's DOM node.\n *\n * @param name - The class name to add to the node.\n *\n * #### Notes\n * If the class name is already added to the node, this is a no-op.\n *\n * The class name must not contain whitespace.\n */\n addClass(name) {\n this.node.classList.add(name);\n }\n /**\n * Remove a class name from the widget's DOM node.\n *\n * @param name - The class name to remove from the node.\n *\n * #### Notes\n * If the class name is not yet added to the node, this is a no-op.\n *\n * The class name must not contain whitespace.\n */\n removeClass(name) {\n this.node.classList.remove(name);\n }\n /**\n * Toggle a class name on the widget's DOM node.\n *\n * @param name - The class name to toggle on the node.\n *\n * @param force - Whether to force add the class (`true`) or force\n * remove the class (`false`). If not provided, the presence of\n * the class will be toggled from its current state.\n *\n * @returns `true` if the class is now present, `false` otherwise.\n *\n * #### Notes\n * The class name must not contain whitespace.\n */\n toggleClass(name, force) {\n if (force === true) {\n this.node.classList.add(name);\n return true;\n }\n if (force === false) {\n this.node.classList.remove(name);\n return false;\n }\n return this.node.classList.toggle(name);\n }\n /**\n * Post an `'update-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for posting the message.\n */\n update() {\n MessageLoop.postMessage(this, Widget.Msg.UpdateRequest);\n }\n /**\n * Post a `'fit-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for posting the message.\n */\n fit() {\n MessageLoop.postMessage(this, Widget.Msg.FitRequest);\n }\n /**\n * Post an `'activate-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for posting the message.\n */\n activate() {\n MessageLoop.postMessage(this, Widget.Msg.ActivateRequest);\n }\n /**\n * Send a `'close-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for sending the message.\n */\n close() {\n MessageLoop.sendMessage(this, Widget.Msg.CloseRequest);\n }\n /**\n * Show the widget and make it visible to its parent widget.\n *\n * #### Notes\n * This causes the {@link isHidden} property to be `false`.\n *\n * If the widget is not explicitly hidden, this is a no-op.\n */\n show() {\n if (!this.testFlag(Widget.Flag.IsHidden)) {\n return;\n }\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.BeforeShow);\n }\n this.clearFlag(Widget.Flag.IsHidden);\n this._toggleHidden(false);\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.AfterShow);\n }\n if (this.parent) {\n let msg = new Widget.ChildMessage('child-shown', this);\n MessageLoop.sendMessage(this.parent, msg);\n }\n }\n /**\n * Hide the widget and make it hidden to its parent widget.\n *\n * #### Notes\n * This causes the {@link isHidden} property to be `true`.\n *\n * If the widget is explicitly hidden, this is a no-op.\n */\n hide() {\n if (this.testFlag(Widget.Flag.IsHidden)) {\n return;\n }\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.BeforeHide);\n }\n this.setFlag(Widget.Flag.IsHidden);\n this._toggleHidden(true);\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.AfterHide);\n }\n if (this.parent) {\n let msg = new Widget.ChildMessage('child-hidden', this);\n MessageLoop.sendMessage(this.parent, msg);\n }\n }\n /**\n * Show or hide the widget according to a boolean value.\n *\n * @param hidden - `true` to hide the widget, or `false` to show it.\n *\n * #### Notes\n * This is a convenience method for `hide()` and `show()`.\n */\n setHidden(hidden) {\n if (hidden) {\n this.hide();\n }\n else {\n this.show();\n }\n }\n /**\n * Test whether the given widget flag is set.\n *\n * #### Notes\n * This will not typically be called directly by user code.\n */\n testFlag(flag) {\n return (this._flags & flag) !== 0;\n }\n /**\n * Set the given widget flag.\n *\n * #### Notes\n * This will not typically be called directly by user code.\n */\n setFlag(flag) {\n this._flags |= flag;\n }\n /**\n * Clear the given widget flag.\n *\n * #### Notes\n * This will not typically be called directly by user code.\n */\n clearFlag(flag) {\n this._flags &= ~flag;\n }\n /**\n * Process a message sent to the widget.\n *\n * @param msg - The message sent to the widget.\n *\n * #### Notes\n * Subclasses may reimplement this method as needed.\n */\n processMessage(msg) {\n switch (msg.type) {\n case 'resize':\n this.notifyLayout(msg);\n this.onResize(msg);\n break;\n case 'update-request':\n this.notifyLayout(msg);\n this.onUpdateRequest(msg);\n break;\n case 'fit-request':\n this.notifyLayout(msg);\n this.onFitRequest(msg);\n break;\n case 'before-show':\n this.notifyLayout(msg);\n this.onBeforeShow(msg);\n break;\n case 'after-show':\n this.setFlag(Widget.Flag.IsVisible);\n this.notifyLayout(msg);\n this.onAfterShow(msg);\n break;\n case 'before-hide':\n this.notifyLayout(msg);\n this.onBeforeHide(msg);\n break;\n case 'after-hide':\n this.clearFlag(Widget.Flag.IsVisible);\n this.notifyLayout(msg);\n this.onAfterHide(msg);\n break;\n case 'before-attach':\n this.notifyLayout(msg);\n this.onBeforeAttach(msg);\n break;\n case 'after-attach':\n if (!this.isHidden && (!this.parent || this.parent.isVisible)) {\n this.setFlag(Widget.Flag.IsVisible);\n }\n this.setFlag(Widget.Flag.IsAttached);\n this.notifyLayout(msg);\n this.onAfterAttach(msg);\n break;\n case 'before-detach':\n this.notifyLayout(msg);\n this.onBeforeDetach(msg);\n break;\n case 'after-detach':\n this.clearFlag(Widget.Flag.IsVisible);\n this.clearFlag(Widget.Flag.IsAttached);\n this.notifyLayout(msg);\n this.onAfterDetach(msg);\n break;\n case 'activate-request':\n this.notifyLayout(msg);\n this.onActivateRequest(msg);\n break;\n case 'close-request':\n this.notifyLayout(msg);\n this.onCloseRequest(msg);\n break;\n case 'child-added':\n this.notifyLayout(msg);\n this.onChildAdded(msg);\n break;\n case 'child-removed':\n this.notifyLayout(msg);\n this.onChildRemoved(msg);\n break;\n default:\n this.notifyLayout(msg);\n break;\n }\n }\n /**\n * Invoke the message processing routine of the widget's layout.\n *\n * @param msg - The message to dispatch to the layout.\n *\n * #### Notes\n * This is a no-op if the widget does not have a layout.\n *\n * This will not typically be called directly by user code.\n */\n notifyLayout(msg) {\n if (this._layout) {\n this._layout.processParentMessage(msg);\n }\n }\n /**\n * A message handler invoked on a `'close-request'` message.\n *\n * #### Notes\n * The default implementation unparents or detaches the widget.\n */\n onCloseRequest(msg) {\n if (this.parent) {\n this.parent = null;\n }\n else if (this.isAttached) {\n Widget.detach(this);\n }\n }\n /**\n * A message handler invoked on a `'resize'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onResize(msg) { }\n /**\n * A message handler invoked on an `'update-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onUpdateRequest(msg) { }\n /**\n * A message handler invoked on a `'fit-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onFitRequest(msg) { }\n /**\n * A message handler invoked on an `'activate-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onActivateRequest(msg) { }\n /**\n * A message handler invoked on a `'before-show'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeShow(msg) { }\n /**\n * A message handler invoked on an `'after-show'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterShow(msg) { }\n /**\n * A message handler invoked on a `'before-hide'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeHide(msg) { }\n /**\n * A message handler invoked on an `'after-hide'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterHide(msg) { }\n /**\n * A message handler invoked on a `'before-attach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeAttach(msg) { }\n /**\n * A message handler invoked on an `'after-attach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterAttach(msg) { }\n /**\n * A message handler invoked on a `'before-detach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeDetach(msg) { }\n /**\n * A message handler invoked on an `'after-detach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterDetach(msg) { }\n /**\n * A message handler invoked on a `'child-added'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildAdded(msg) { }\n /**\n * A message handler invoked on a `'child-removed'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildRemoved(msg) { }\n _toggleHidden(hidden) {\n if (hidden) {\n switch (this._hiddenMode) {\n case Widget.HiddenMode.Display:\n this.addClass('lm-mod-hidden');\n break;\n case Widget.HiddenMode.Scale:\n this.node.style.transform = 'scale(0)';\n this.node.setAttribute('aria-hidden', 'true');\n break;\n case Widget.HiddenMode.ContentVisibility:\n // @ts-expect-error content-visibility unknown by DOM lib types\n this.node.style.contentVisibility = 'hidden';\n this.node.style.zIndex = '-1';\n break;\n }\n }\n else {\n switch (this._hiddenMode) {\n case Widget.HiddenMode.Display:\n this.removeClass('lm-mod-hidden');\n break;\n case Widget.HiddenMode.Scale:\n this.node.style.transform = '';\n this.node.removeAttribute('aria-hidden');\n break;\n case Widget.HiddenMode.ContentVisibility:\n // @ts-expect-error content-visibility unknown by DOM lib types\n this.node.style.contentVisibility = '';\n this.node.style.zIndex = '';\n break;\n }\n }\n }\n}\n/**\n * The namespace for the `Widget` class statics.\n */\n(function (Widget) {\n (function (HiddenMode) {\n /**\n * Set a `lm-mod-hidden` CSS class to hide the widget using `display:none`\n * CSS from the standard Lumino CSS.\n */\n HiddenMode[HiddenMode[\"Display\"] = 0] = \"Display\";\n /**\n * Hide the widget by setting the `transform` to `'scale(0)'`.\n */\n HiddenMode[HiddenMode[\"Scale\"] = 1] = \"Scale\";\n /**\n *Hide the widget by setting the `content-visibility` to `'hidden'`.\n */\n HiddenMode[HiddenMode[\"ContentVisibility\"] = 2] = \"ContentVisibility\";\n })(Widget.HiddenMode || (Widget.HiddenMode = {}));\n (function (Flag) {\n /**\n * The widget has been disposed.\n */\n Flag[Flag[\"IsDisposed\"] = 1] = \"IsDisposed\";\n /**\n * The widget is attached to the DOM.\n */\n Flag[Flag[\"IsAttached\"] = 2] = \"IsAttached\";\n /**\n * The widget is hidden.\n */\n Flag[Flag[\"IsHidden\"] = 4] = \"IsHidden\";\n /**\n * The widget is visible.\n */\n Flag[Flag[\"IsVisible\"] = 8] = \"IsVisible\";\n /**\n * A layout cannot be set on the widget.\n */\n Flag[Flag[\"DisallowLayout\"] = 16] = \"DisallowLayout\";\n })(Widget.Flag || (Widget.Flag = {}));\n (function (Msg) {\n /**\n * A singleton `'before-show'` message.\n *\n * #### Notes\n * This message is sent to a widget before it becomes visible.\n *\n * This message is **not** sent when the widget is being attached.\n */\n Msg.BeforeShow = new Message('before-show');\n /**\n * A singleton `'after-show'` message.\n *\n * #### Notes\n * This message is sent to a widget after it becomes visible.\n *\n * This message is **not** sent when the widget is being attached.\n */\n Msg.AfterShow = new Message('after-show');\n /**\n * A singleton `'before-hide'` message.\n *\n * #### Notes\n * This message is sent to a widget before it becomes not-visible.\n *\n * This message is **not** sent when the widget is being detached.\n */\n Msg.BeforeHide = new Message('before-hide');\n /**\n * A singleton `'after-hide'` message.\n *\n * #### Notes\n * This message is sent to a widget after it becomes not-visible.\n *\n * This message is **not** sent when the widget is being detached.\n */\n Msg.AfterHide = new Message('after-hide');\n /**\n * A singleton `'before-attach'` message.\n *\n * #### Notes\n * This message is sent to a widget before it is attached.\n */\n Msg.BeforeAttach = new Message('before-attach');\n /**\n * A singleton `'after-attach'` message.\n *\n * #### Notes\n * This message is sent to a widget after it is attached.\n */\n Msg.AfterAttach = new Message('after-attach');\n /**\n * A singleton `'before-detach'` message.\n *\n * #### Notes\n * This message is sent to a widget before it is detached.\n */\n Msg.BeforeDetach = new Message('before-detach');\n /**\n * A singleton `'after-detach'` message.\n *\n * #### Notes\n * This message is sent to a widget after it is detached.\n */\n Msg.AfterDetach = new Message('after-detach');\n /**\n * A singleton `'parent-changed'` message.\n *\n * #### Notes\n * This message is sent to a widget when its parent has changed.\n */\n Msg.ParentChanged = new Message('parent-changed');\n /**\n * A singleton conflatable `'update-request'` message.\n *\n * #### Notes\n * This message can be dispatched to supporting widgets in order to\n * update their content based on the current widget state. Not all\n * widgets will respond to messages of this type.\n *\n * For widgets with a layout, this message will inform the layout to\n * update the position and size of its child widgets.\n */\n Msg.UpdateRequest = new ConflatableMessage('update-request');\n /**\n * A singleton conflatable `'fit-request'` message.\n *\n * #### Notes\n * For widgets with a layout, this message will inform the layout to\n * recalculate its size constraints to fit the space requirements of\n * its child widgets, and to update their position and size. Not all\n * layouts will respond to messages of this type.\n */\n Msg.FitRequest = new ConflatableMessage('fit-request');\n /**\n * A singleton conflatable `'activate-request'` message.\n *\n * #### Notes\n * This message should be dispatched to a widget when it should\n * perform the actions necessary to activate the widget, which\n * may include focusing its node or descendant node.\n */\n Msg.ActivateRequest = new ConflatableMessage('activate-request');\n /**\n * A singleton conflatable `'close-request'` message.\n *\n * #### Notes\n * This message should be dispatched to a widget when it should close\n * and remove itself from the widget hierarchy.\n */\n Msg.CloseRequest = new ConflatableMessage('close-request');\n })(Widget.Msg || (Widget.Msg = {}));\n /**\n * A message class for child related messages.\n */\n class ChildMessage extends Message {\n /**\n * Construct a new child message.\n *\n * @param type - The message type.\n *\n * @param child - The child widget for the message.\n */\n constructor(type, child) {\n super(type);\n this.child = child;\n }\n }\n Widget.ChildMessage = ChildMessage;\n /**\n * A message class for `'resize'` messages.\n */\n class ResizeMessage extends Message {\n /**\n * Construct a new resize message.\n *\n * @param width - The **offset width** of the widget, or `-1` if\n * the width is not known.\n *\n * @param height - The **offset height** of the widget, or `-1` if\n * the height is not known.\n */\n constructor(width, height) {\n super('resize');\n this.width = width;\n this.height = height;\n }\n }\n Widget.ResizeMessage = ResizeMessage;\n /**\n * The namespace for the `ResizeMessage` class statics.\n */\n (function (ResizeMessage) {\n /**\n * A singleton `'resize'` message with an unknown size.\n */\n ResizeMessage.UnknownSize = new ResizeMessage(-1, -1);\n })(ResizeMessage = Widget.ResizeMessage || (Widget.ResizeMessage = {}));\n /**\n * Attach a widget to a host DOM node.\n *\n * @param widget - The widget of interest.\n *\n * @param host - The DOM node to use as the widget's host.\n *\n * @param ref - The child of `host` to use as the reference element.\n * If this is provided, the widget will be inserted before this\n * node in the host. The default is `null`, which will cause the\n * widget to be added as the last child of the host.\n *\n * #### Notes\n * This will throw an error if the widget is not a root widget, if\n * the widget is already attached, or if the host is not attached\n * to the DOM.\n */\n function attach(widget, host, ref = null) {\n if (widget.parent) {\n throw new Error('Cannot attach a child widget.');\n }\n if (widget.isAttached || widget.node.isConnected) {\n throw new Error('Widget is already attached.');\n }\n if (!host.isConnected) {\n throw new Error('Host is not attached.');\n }\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n host.insertBefore(widget.node, ref);\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n Widget.attach = attach;\n /**\n * Detach the widget from its host DOM node.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * This will throw an error if the widget is not a root widget,\n * or if the widget is not attached to the DOM.\n */\n function detach(widget) {\n if (widget.parent) {\n throw new Error('Cannot detach a child widget.');\n }\n if (!widget.isAttached || !widget.node.isConnected) {\n throw new Error('Widget is not attached.');\n }\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n widget.node.parentNode.removeChild(widget.node);\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n Widget.detach = detach;\n})(Widget || (Widget = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$j;\n(function (Private) {\n /**\n * An attached property for the widget title object.\n */\n Private.titleProperty = new AttachedProperty({\n name: 'title',\n create: owner => new Title({ owner })\n });\n /**\n * Create a DOM node for the given widget options.\n */\n function createNode(options) {\n return options.node || document.createElement(options.tag || 'div');\n }\n Private.createNode = createNode;\n})(Private$j || (Private$j = {}));\n\n/**\n * An abstract base class for creating lumino layouts.\n *\n * #### Notes\n * A layout is used to add widgets to a parent and to arrange those\n * widgets within the parent's DOM node.\n *\n * This class implements the base functionality which is required of\n * nearly all layouts. It must be subclassed in order to be useful.\n *\n * Notably, this class does not define a uniform interface for adding\n * widgets to the layout. A subclass should define that API in a way\n * which is meaningful for its intended use.\n */\nclass Layout {\n /**\n * Construct a new layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options = {}) {\n this._disposed = false;\n this._parent = null;\n this._fitPolicy = options.fitPolicy || 'set-min-size';\n }\n /**\n * Dispose of the resources held by the layout.\n *\n * #### Notes\n * This should be reimplemented to clear and dispose of the widgets.\n *\n * All reimplementations should call the superclass method.\n *\n * This method is called automatically when the parent is disposed.\n */\n dispose() {\n this._parent = null;\n this._disposed = true;\n Signal.clearData(this);\n AttachedProperty.clearData(this);\n }\n /**\n * Test whether the layout is disposed.\n */\n get isDisposed() {\n return this._disposed;\n }\n /**\n * Get the parent widget of the layout.\n */\n get parent() {\n return this._parent;\n }\n /**\n * Set the parent widget of the layout.\n *\n * #### Notes\n * This is set automatically when installing the layout on the parent\n * widget. The parent widget should not be set directly by user code.\n */\n set parent(value) {\n if (this._parent === value) {\n return;\n }\n if (this._parent) {\n throw new Error('Cannot change parent widget.');\n }\n if (value.layout !== this) {\n throw new Error('Invalid parent widget.');\n }\n this._parent = value;\n this.init();\n }\n /**\n * Get the fit policy for the layout.\n *\n * #### Notes\n * The fit policy controls the computed size constraints which are\n * applied to the parent widget by the layout.\n *\n * Some layout implementations may ignore the fit policy.\n */\n get fitPolicy() {\n return this._fitPolicy;\n }\n /**\n * Set the fit policy for the layout.\n *\n * #### Notes\n * The fit policy controls the computed size constraints which are\n * applied to the parent widget by the layout.\n *\n * Some layout implementations may ignore the fit policy.\n *\n * Changing the fit policy will clear the current size constraint\n * for the parent widget and then re-fit the parent.\n */\n set fitPolicy(value) {\n // Bail if the policy does not change\n if (this._fitPolicy === value) {\n return;\n }\n // Update the internal policy.\n this._fitPolicy = value;\n // Clear the size constraints and schedule a fit of the parent.\n if (this._parent) {\n let style = this._parent.node.style;\n style.minWidth = '';\n style.minHeight = '';\n style.maxWidth = '';\n style.maxHeight = '';\n this._parent.fit();\n }\n }\n /**\n * Process a message sent to the parent widget.\n *\n * @param msg - The message sent to the parent widget.\n *\n * #### Notes\n * This method is called by the parent widget to process a message.\n *\n * Subclasses may reimplement this method as needed.\n */\n processParentMessage(msg) {\n switch (msg.type) {\n case 'resize':\n this.onResize(msg);\n break;\n case 'update-request':\n this.onUpdateRequest(msg);\n break;\n case 'fit-request':\n this.onFitRequest(msg);\n break;\n case 'before-show':\n this.onBeforeShow(msg);\n break;\n case 'after-show':\n this.onAfterShow(msg);\n break;\n case 'before-hide':\n this.onBeforeHide(msg);\n break;\n case 'after-hide':\n this.onAfterHide(msg);\n break;\n case 'before-attach':\n this.onBeforeAttach(msg);\n break;\n case 'after-attach':\n this.onAfterAttach(msg);\n break;\n case 'before-detach':\n this.onBeforeDetach(msg);\n break;\n case 'after-detach':\n this.onAfterDetach(msg);\n break;\n case 'child-removed':\n this.onChildRemoved(msg);\n break;\n case 'child-shown':\n this.onChildShown(msg);\n break;\n case 'child-hidden':\n this.onChildHidden(msg);\n break;\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n *\n * #### Notes\n * This method is invoked immediately after the layout is installed\n * on the parent widget.\n *\n * The default implementation reparents all of the widgets to the\n * layout parent widget.\n *\n * Subclasses should reimplement this method and attach the child\n * widget nodes to the parent widget's node.\n */\n init() {\n for (const widget of this) {\n widget.parent = this.parent;\n }\n }\n /**\n * A message handler invoked on a `'resize'` message.\n *\n * #### Notes\n * The layout should ensure that its widgets are resized according\n * to the specified layout space, and that they are sent a `'resize'`\n * message if appropriate.\n *\n * The default implementation of this method sends an `UnknownSize`\n * resize message to all widgets.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onResize(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, Widget.ResizeMessage.UnknownSize);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n *\n * #### Notes\n * The layout should ensure that its widgets are resized according\n * to the available layout space, and that they are sent a `'resize'`\n * message if appropriate.\n *\n * The default implementation of this method sends an `UnknownSize`\n * resize message to all widgets.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onUpdateRequest(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, Widget.ResizeMessage.UnknownSize);\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeAttach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on an `'after-attach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterAttach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on a `'before-detach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeDetach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterDetach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeShow(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on an `'after-show'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterShow(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on a `'before-hide'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeHide(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on an `'after-hide'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterHide(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n *\n * #### Notes\n * This will remove the child widget from the layout.\n *\n * Subclasses should **not** typically reimplement this method.\n */\n onChildRemoved(msg) {\n this.removeWidget(msg.child);\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onFitRequest(msg) { }\n /**\n * A message handler invoked on a `'child-shown'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildShown(msg) { }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildHidden(msg) { }\n}\n/**\n * The namespace for the `Layout` class statics.\n */\n(function (Layout) {\n /**\n * Get the horizontal alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The horizontal alignment for the widget.\n *\n * #### Notes\n * If the layout width allocated to a widget is larger than its max\n * width, the horizontal alignment controls how the widget is placed\n * within the extra horizontal space.\n *\n * If the allocated width is less than the widget's max width, the\n * horizontal alignment has no effect.\n *\n * Some layout implementations may ignore horizontal alignment.\n */\n function getHorizontalAlignment(widget) {\n return Private$i.horizontalAlignmentProperty.get(widget);\n }\n Layout.getHorizontalAlignment = getHorizontalAlignment;\n /**\n * Set the horizontal alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the horizontal alignment.\n *\n * #### Notes\n * If the layout width allocated to a widget is larger than its max\n * width, the horizontal alignment controls how the widget is placed\n * within the extra horizontal space.\n *\n * If the allocated width is less than the widget's max width, the\n * horizontal alignment has no effect.\n *\n * Some layout implementations may ignore horizontal alignment.\n *\n * Changing the horizontal alignment will post an `update-request`\n * message to widget's parent, provided the parent has a layout\n * installed.\n */\n function setHorizontalAlignment(widget, value) {\n Private$i.horizontalAlignmentProperty.set(widget, value);\n }\n Layout.setHorizontalAlignment = setHorizontalAlignment;\n /**\n * Get the vertical alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The vertical alignment for the widget.\n *\n * #### Notes\n * If the layout height allocated to a widget is larger than its max\n * height, the vertical alignment controls how the widget is placed\n * within the extra vertical space.\n *\n * If the allocated height is less than the widget's max height, the\n * vertical alignment has no effect.\n *\n * Some layout implementations may ignore vertical alignment.\n */\n function getVerticalAlignment(widget) {\n return Private$i.verticalAlignmentProperty.get(widget);\n }\n Layout.getVerticalAlignment = getVerticalAlignment;\n /**\n * Set the vertical alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the vertical alignment.\n *\n * #### Notes\n * If the layout height allocated to a widget is larger than its max\n * height, the vertical alignment controls how the widget is placed\n * within the extra vertical space.\n *\n * If the allocated height is less than the widget's max height, the\n * vertical alignment has no effect.\n *\n * Some layout implementations may ignore vertical alignment.\n *\n * Changing the horizontal alignment will post an `update-request`\n * message to widget's parent, provided the parent has a layout\n * installed.\n */\n function setVerticalAlignment(widget, value) {\n Private$i.verticalAlignmentProperty.set(widget, value);\n }\n Layout.setVerticalAlignment = setVerticalAlignment;\n})(Layout || (Layout = {}));\n/**\n * An object which assists in the absolute layout of widgets.\n *\n * #### Notes\n * This class is useful when implementing a layout which arranges its\n * widgets using absolute positioning.\n *\n * This class is used by nearly all of the built-in lumino layouts.\n */\nclass LayoutItem {\n /**\n * Construct a new layout item.\n *\n * @param widget - The widget to be managed by the item.\n *\n * #### Notes\n * The widget will be set to absolute positioning.\n * The widget will use strict CSS containment.\n */\n constructor(widget) {\n this._top = NaN;\n this._left = NaN;\n this._width = NaN;\n this._height = NaN;\n this._minWidth = 0;\n this._minHeight = 0;\n this._maxWidth = Infinity;\n this._maxHeight = Infinity;\n this._disposed = false;\n this.widget = widget;\n this.widget.node.style.position = 'absolute';\n this.widget.node.style.contain = 'strict';\n }\n /**\n * Dispose of the the layout item.\n *\n * #### Notes\n * This will reset the positioning of the widget.\n */\n dispose() {\n // Do nothing if the item is already disposed.\n if (this._disposed) {\n return;\n }\n // Mark the item as disposed.\n this._disposed = true;\n // Reset the widget style.\n let style = this.widget.node.style;\n style.position = '';\n style.top = '';\n style.left = '';\n style.width = '';\n style.height = '';\n style.contain = '';\n }\n /**\n * The computed minimum width of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get minWidth() {\n return this._minWidth;\n }\n /**\n * The computed minimum height of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get minHeight() {\n return this._minHeight;\n }\n /**\n * The computed maximum width of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get maxWidth() {\n return this._maxWidth;\n }\n /**\n * The computed maximum height of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get maxHeight() {\n return this._maxHeight;\n }\n /**\n * Whether the layout item is disposed.\n */\n get isDisposed() {\n return this._disposed;\n }\n /**\n * Whether the managed widget is hidden.\n */\n get isHidden() {\n return this.widget.isHidden;\n }\n /**\n * Whether the managed widget is visible.\n */\n get isVisible() {\n return this.widget.isVisible;\n }\n /**\n * Whether the managed widget is attached.\n */\n get isAttached() {\n return this.widget.isAttached;\n }\n /**\n * Update the computed size limits of the managed widget.\n */\n fit() {\n let limits = ElementExt.sizeLimits(this.widget.node);\n this._minWidth = limits.minWidth;\n this._minHeight = limits.minHeight;\n this._maxWidth = limits.maxWidth;\n this._maxHeight = limits.maxHeight;\n }\n /**\n * Update the position and size of the managed widget.\n *\n * @param left - The left edge position of the layout box.\n *\n * @param top - The top edge position of the layout box.\n *\n * @param width - The width of the layout box.\n *\n * @param height - The height of the layout box.\n */\n update(left, top, width, height) {\n // Clamp the size to the computed size limits.\n let clampW = Math.max(this._minWidth, Math.min(width, this._maxWidth));\n let clampH = Math.max(this._minHeight, Math.min(height, this._maxHeight));\n // Adjust the left edge for the horizontal alignment, if needed.\n if (clampW < width) {\n switch (Layout.getHorizontalAlignment(this.widget)) {\n case 'left':\n break;\n case 'center':\n left += (width - clampW) / 2;\n break;\n case 'right':\n left += width - clampW;\n break;\n default:\n throw 'unreachable';\n }\n }\n // Adjust the top edge for the vertical alignment, if needed.\n if (clampH < height) {\n switch (Layout.getVerticalAlignment(this.widget)) {\n case 'top':\n break;\n case 'center':\n top += (height - clampH) / 2;\n break;\n case 'bottom':\n top += height - clampH;\n break;\n default:\n throw 'unreachable';\n }\n }\n // Set up the resize variables.\n let resized = false;\n let style = this.widget.node.style;\n // Update the top edge of the widget if needed.\n if (this._top !== top) {\n this._top = top;\n style.top = `${top}px`;\n }\n // Update the left edge of the widget if needed.\n if (this._left !== left) {\n this._left = left;\n style.left = `${left}px`;\n }\n // Update the width of the widget if needed.\n if (this._width !== clampW) {\n resized = true;\n this._width = clampW;\n style.width = `${clampW}px`;\n }\n // Update the height of the widget if needed.\n if (this._height !== clampH) {\n resized = true;\n this._height = clampH;\n style.height = `${clampH}px`;\n }\n // Send a resize message to the widget if needed.\n if (resized) {\n let msg = new Widget.ResizeMessage(clampW, clampH);\n MessageLoop.sendMessage(this.widget, msg);\n }\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$i;\n(function (Private) {\n /**\n * The attached property for a widget horizontal alignment.\n */\n Private.horizontalAlignmentProperty = new AttachedProperty({\n name: 'horizontalAlignment',\n create: () => 'center',\n changed: onAlignmentChanged\n });\n /**\n * The attached property for a widget vertical alignment.\n */\n Private.verticalAlignmentProperty = new AttachedProperty({\n name: 'verticalAlignment',\n create: () => 'top',\n changed: onAlignmentChanged\n });\n /**\n * The change handler for the attached alignment properties.\n */\n function onAlignmentChanged(child) {\n if (child.parent && child.parent.layout) {\n child.parent.update();\n }\n }\n})(Private$i || (Private$i = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A concrete layout implementation suitable for many use cases.\n *\n * #### Notes\n * This class is suitable as a base class for implementing a variety of\n * layouts, but can also be used directly with standard CSS to layout a\n * collection of widgets.\n */\nclass PanelLayout extends Layout {\n constructor() {\n super(...arguments);\n this._widgets = [];\n }\n /**\n * Dispose of the resources held by the layout.\n *\n * #### Notes\n * This will clear and dispose all widgets in the layout.\n *\n * All reimplementations should call the superclass method.\n *\n * This method is called automatically when the parent is disposed.\n */\n dispose() {\n while (this._widgets.length > 0) {\n this._widgets.pop().dispose();\n }\n super.dispose();\n }\n /**\n * A read-only array of the widgets in the layout.\n */\n get widgets() {\n return this._widgets;\n }\n /**\n * Create an iterator over the widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n */\n *[Symbol.iterator]() {\n yield* this._widgets;\n }\n /**\n * Add a widget to the end of the layout.\n *\n * @param widget - The widget to add to the layout.\n *\n * #### Notes\n * If the widget is already contained in the layout, it will be moved.\n */\n addWidget(widget) {\n this.insertWidget(this._widgets.length, widget);\n }\n /**\n * Insert a widget into the layout at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into the layout.\n *\n * #### Notes\n * The index will be clamped to the bounds of the widgets.\n *\n * If the widget is already added to the layout, it will be moved.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n */\n insertWidget(index, widget) {\n // Remove the widget from its current parent. This is a no-op\n // if the widget's parent is already the layout parent widget.\n widget.parent = this.parent;\n // Look up the current index of the widget.\n let i = this._widgets.indexOf(widget);\n // Clamp the insert index to the array bounds.\n let j = Math.max(0, Math.min(index, this._widgets.length));\n // If the widget is not in the array, insert it.\n if (i === -1) {\n // Insert the widget into the array.\n ArrayExt.insert(this._widgets, j, widget);\n // If the layout is parented, attach the widget to the DOM.\n if (this.parent) {\n this.attachWidget(j, widget);\n }\n // There is nothing more to do.\n return;\n }\n // Otherwise, the widget exists in the array and should be moved.\n // Adjust the index if the location is at the end of the array.\n if (j === this._widgets.length) {\n j--;\n }\n // Bail if there is no effective move.\n if (i === j) {\n return;\n }\n // Move the widget to the new location.\n ArrayExt.move(this._widgets, i, j);\n // If the layout is parented, move the widget in the DOM.\n if (this.parent) {\n this.moveWidget(i, j, widget);\n }\n }\n /**\n * Remove a widget from the layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n this.removeWidgetAt(this._widgets.indexOf(widget));\n }\n /**\n * Remove the widget at a given index from the layout.\n *\n * @param index - The index of the widget to remove.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n */\n removeWidgetAt(index) {\n // Remove the widget from the array.\n let widget = ArrayExt.removeAt(this._widgets, index);\n // If the layout is parented, detach the widget from the DOM.\n if (widget && this.parent) {\n this.detachWidget(index, widget);\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n super.init();\n let index = 0;\n for (const widget of this) {\n this.attachWidget(index++, widget);\n }\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This method is called automatically by the panel layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation adds the widgets's node to the parent's\n * node at the proper location, and sends the appropriate attach\n * messages to the widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is added to the parent's node.\n */\n attachWidget(index, widget) {\n // Look up the next sibling reference node.\n let ref = this.parent.node.children[index];\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Insert the widget's node before the sibling.\n this.parent.node.insertBefore(widget.node, ref);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This method is called automatically by the panel layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation moves the widget's node to the proper\n * location in the parent's node and sends the appropriate attach and\n * detach messages to the widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is moved in the parent's node.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` and message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Look up the next sibling reference node.\n let ref = this.parent.node.children[toIndex];\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Insert the widget's node before the sibling.\n this.parent.node.insertBefore(widget.node, ref);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This method is called automatically by the panel layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation removes the widget's node from the\n * parent's node, and sends the appropriate detach messages to the\n * widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is removed from the parent's node.\n */\n detachWidget(index, widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n }\n}\n\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nvar Utils;\n(function (Utils) {\n /**\n * Clamp a dimension value to an integer >= 0.\n */\n function clampDimension(value) {\n return Math.max(0, Math.floor(value));\n }\n Utils.clampDimension = clampDimension;\n})(Utils || (Utils = {}));\nvar Utils$1 = Utils;\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which arranges its widgets into resizable sections.\n */\nclass SplitLayout extends PanelLayout {\n /**\n * Construct a new split layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options) {\n super();\n this.widgetOffset = 0;\n this._fixed = 0;\n this._spacing = 4;\n this._dirty = false;\n this._hasNormedSizes = false;\n this._sizers = [];\n this._items = [];\n this._handles = [];\n this._box = null;\n this._alignment = 'start';\n this._orientation = 'horizontal';\n this.renderer = options.renderer;\n if (options.orientation !== undefined) {\n this._orientation = options.orientation;\n }\n if (options.alignment !== undefined) {\n this._alignment = options.alignment;\n }\n if (options.spacing !== undefined) {\n this._spacing = Utils.clampDimension(options.spacing);\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the layout items.\n for (const item of this._items) {\n item.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n this._sizers.length = 0;\n this._handles.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Get the layout orientation for the split layout.\n */\n get orientation() {\n return this._orientation;\n }\n /**\n * Set the layout orientation for the split layout.\n */\n set orientation(value) {\n if (this._orientation === value) {\n return;\n }\n this._orientation = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['orientation'] = value;\n this.parent.fit();\n }\n /**\n * Get the content alignment for the split layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split layout.\n */\n get alignment() {\n return this._alignment;\n }\n /**\n * Set the content alignment for the split layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split layout.\n */\n set alignment(value) {\n if (this._alignment === value) {\n return;\n }\n this._alignment = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['alignment'] = value;\n this.parent.update();\n }\n /**\n * Get the inter-element spacing for the split layout.\n */\n get spacing() {\n return this._spacing;\n }\n /**\n * Set the inter-element spacing for the split layout.\n */\n set spacing(value) {\n value = Utils.clampDimension(value);\n if (this._spacing === value) {\n return;\n }\n this._spacing = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * A read-only array of the split handles in the layout.\n */\n get handles() {\n return this._handles;\n }\n /**\n * Get the absolute sizes of the widgets in the layout.\n *\n * @returns A new array of the absolute sizes of the widgets.\n *\n * This method **does not** measure the DOM nodes.\n */\n absoluteSizes() {\n return this._sizers.map(sizer => sizer.size);\n }\n /**\n * Get the relative sizes of the widgets in the layout.\n *\n * @returns A new array of the relative sizes of the widgets.\n *\n * #### Notes\n * The returned sizes reflect the sizes of the widgets normalized\n * relative to their siblings.\n *\n * This method **does not** measure the DOM nodes.\n */\n relativeSizes() {\n return Private$h.normalize(this._sizers.map(sizer => sizer.size));\n }\n /**\n * Set the relative sizes for the widgets in the layout.\n *\n * @param sizes - The relative sizes for the widgets in the panel.\n * @param update - Update the layout after setting relative sizes.\n * Default is True.\n *\n * #### Notes\n * Extra values are ignored, too few will yield an undefined layout.\n *\n * The actual geometry of the DOM nodes is updated asynchronously.\n */\n setRelativeSizes(sizes, update = true) {\n // Copy the sizes and pad with zeros as needed.\n let n = this._sizers.length;\n let temp = sizes.slice(0, n);\n while (temp.length < n) {\n temp.push(0);\n }\n // Normalize the padded sizes.\n let normed = Private$h.normalize(temp);\n // Apply the normalized sizes to the sizers.\n for (let i = 0; i < n; ++i) {\n let sizer = this._sizers[i];\n sizer.sizeHint = normed[i];\n sizer.size = normed[i];\n }\n // Set the flag indicating the sizes are normalized.\n this._hasNormedSizes = true;\n // Trigger an update of the parent widget.\n if (update && this.parent) {\n this.parent.update();\n }\n }\n /**\n * Move the offset position of a split handle.\n *\n * @param index - The index of the handle of the interest.\n *\n * @param position - The desired offset position of the handle.\n *\n * #### Notes\n * The position is relative to the offset parent.\n *\n * This will move the handle as close as possible to the desired\n * position. The sibling widgets will be adjusted as necessary.\n */\n moveHandle(index, position) {\n // Bail if the index is invalid or the handle is hidden.\n let handle = this._handles[index];\n if (!handle || handle.classList.contains('lm-mod-hidden')) {\n return;\n }\n // Compute the desired delta movement for the handle.\n let delta;\n if (this._orientation === 'horizontal') {\n delta = position - handle.offsetLeft;\n }\n else {\n delta = position - handle.offsetTop;\n }\n // Bail if there is no handle movement.\n if (delta === 0) {\n return;\n }\n // Prevent widget resizing unless needed.\n for (let sizer of this._sizers) {\n if (sizer.size > 0) {\n sizer.sizeHint = sizer.size;\n }\n }\n // Adjust the sizers to reflect the handle movement.\n BoxEngine.adjust(this._sizers, index, delta);\n // Update the layout of the widgets.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n this.parent.dataset['orientation'] = this.orientation;\n this.parent.dataset['alignment'] = this.alignment;\n super.init();\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n attachWidget(index, widget) {\n // Create the item, handle, and sizer for the new widget.\n let item = new LayoutItem(widget);\n let handle = Private$h.createHandle(this.renderer);\n let average = Private$h.averageSize(this._sizers);\n let sizer = Private$h.createSizer(average);\n // Insert the item, handle, and sizer into the internal arrays.\n ArrayExt.insert(this._items, index, item);\n ArrayExt.insert(this._sizers, index, sizer);\n ArrayExt.insert(this._handles, index, handle);\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget and handle nodes to the parent.\n this.parent.node.appendChild(widget.node);\n this.parent.node.appendChild(handle);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Move the item, sizer, and handle for the widget.\n ArrayExt.move(this._items, fromIndex, toIndex);\n ArrayExt.move(this._sizers, fromIndex, toIndex);\n ArrayExt.move(this._handles, fromIndex, toIndex);\n // Post a fit request to the parent to show/hide last handle.\n this.parent.fit();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n // Remove the item, handle, and sizer for the widget.\n let item = ArrayExt.removeAt(this._items, index);\n let handle = ArrayExt.removeAt(this._handles, index);\n ArrayExt.removeAt(this._sizers, index);\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget and handle nodes from the parent.\n this.parent.node.removeChild(widget.node);\n this.parent.node.removeChild(handle);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Dispose of the layout item.\n item.dispose();\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Update the item position.\n *\n * @param i Item index\n * @param isHorizontal Whether the layout is horizontal or not\n * @param left Left position in pixels\n * @param top Top position in pixels\n * @param height Item height\n * @param width Item width\n * @param size Item size\n */\n updateItemPosition(i, isHorizontal, left, top, height, width, size) {\n const item = this._items[i];\n if (item.isHidden) {\n return;\n }\n // Fetch the style for the handle.\n let handleStyle = this._handles[i].style;\n // Update the widget and handle, and advance the relevant edge.\n if (isHorizontal) {\n left += this.widgetOffset;\n item.update(left, top, size, height);\n left += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${this._spacing}px`;\n handleStyle.height = `${height}px`;\n }\n else {\n top += this.widgetOffset;\n item.update(left, top, width, size);\n top += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${width}px`;\n handleStyle.height = `${this._spacing}px`;\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Update the handles and track the visible widget count.\n let nVisible = 0;\n let lastHandleIndex = -1;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n if (this._items[i].isHidden) {\n this._handles[i].classList.add('lm-mod-hidden');\n }\n else {\n this._handles[i].classList.remove('lm-mod-hidden');\n lastHandleIndex = i;\n nVisible++;\n }\n }\n // Hide the handle for the last visible widget.\n if (lastHandleIndex !== -1) {\n this._handles[lastHandleIndex].classList.add('lm-mod-hidden');\n }\n // Update the fixed space for the visible items.\n this._fixed =\n this._spacing * Math.max(0, nVisible - 1) +\n this.widgetOffset * this._items.length;\n // Setup the computed minimum size.\n let horz = this._orientation === 'horizontal';\n let minW = horz ? this._fixed : 0;\n let minH = horz ? 0 : this._fixed;\n // Update the sizers and computed size limits.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item and corresponding box sizer.\n let item = this._items[i];\n let sizer = this._sizers[i];\n // Prevent resizing unless necessary.\n if (sizer.size > 0) {\n sizer.sizeHint = sizer.size;\n }\n // If the item is hidden, it should consume zero size.\n if (item.isHidden) {\n sizer.minSize = 0;\n sizer.maxSize = 0;\n continue;\n }\n // Update the size limits for the item.\n item.fit();\n // Update the stretch factor.\n sizer.stretch = SplitLayout.getStretch(item.widget);\n // Update the sizer limits and computed min size.\n if (horz) {\n sizer.minSize = item.minWidth;\n sizer.maxSize = item.maxWidth;\n minW += item.minWidth;\n minH = Math.max(minH, item.minHeight);\n }\n else {\n sizer.minSize = item.minHeight;\n sizer.maxSize = item.maxHeight;\n minH += item.minHeight;\n minW = Math.max(minW, item.minWidth);\n }\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Bail early if there are no visible items to layout.\n if (nVisible === 0 && this.widgetOffset === 0) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the actual layout bounds adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Set up the variables for justification and alignment offset.\n let extra = 0;\n let offset = 0;\n let horz = this._orientation === 'horizontal';\n if (nVisible > 0) {\n // Compute the adjusted layout space.\n let space;\n if (horz) {\n // left += this.widgetOffset;\n space = Math.max(0, width - this._fixed);\n }\n else {\n // top += this.widgetOffset;\n space = Math.max(0, height - this._fixed);\n }\n // Scale the size hints if they are normalized.\n if (this._hasNormedSizes) {\n for (let sizer of this._sizers) {\n sizer.sizeHint *= space;\n }\n this._hasNormedSizes = false;\n }\n // Distribute the layout space to the box sizers.\n let delta = BoxEngine.calc(this._sizers, space);\n // Account for alignment if there is extra layout space.\n if (delta > 0) {\n switch (this._alignment) {\n case 'start':\n break;\n case 'center':\n extra = 0;\n offset = delta / 2;\n break;\n case 'end':\n extra = 0;\n offset = delta;\n break;\n case 'justify':\n extra = delta / nVisible;\n offset = 0;\n break;\n default:\n throw 'unreachable';\n }\n }\n }\n // Layout the items using the computed box sizes.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n const item = this._items[i];\n // Fetch the computed size for the widget.\n const size = item.isHidden ? 0 : this._sizers[i].size + extra;\n this.updateItemPosition(i, horz, horz ? left + offset : left, horz ? top : top + offset, height, width, size);\n const fullOffset = this.widgetOffset +\n (this._handles[i].classList.contains('lm-mod-hidden')\n ? 0\n : this._spacing);\n if (horz) {\n left += size + fullOffset;\n }\n else {\n top += size + fullOffset;\n }\n }\n }\n}\n/**\n * The namespace for the `SplitLayout` class statics.\n */\n(function (SplitLayout) {\n /**\n * Get the split layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The split layout stretch factor for the widget.\n */\n function getStretch(widget) {\n return Private$h.stretchProperty.get(widget);\n }\n SplitLayout.getStretch = getStretch;\n /**\n * Set the split layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n Private$h.stretchProperty.set(widget, value);\n }\n SplitLayout.setStretch = setStretch;\n})(SplitLayout || (SplitLayout = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$h;\n(function (Private) {\n /**\n * The property descriptor for a widget stretch factor.\n */\n Private.stretchProperty = new AttachedProperty({\n name: 'stretch',\n create: () => 0,\n coerce: (owner, value) => Math.max(0, Math.floor(value)),\n changed: onChildSizingChanged\n });\n /**\n * Create a new box sizer with the given size hint.\n */\n function createSizer(size) {\n let sizer = new BoxSizer();\n sizer.sizeHint = Math.floor(size);\n return sizer;\n }\n Private.createSizer = createSizer;\n /**\n * Create a new split handle node using the given renderer.\n */\n function createHandle(renderer) {\n let handle = renderer.createHandle();\n handle.style.position = 'absolute';\n // Do not use size containment to allow the handle to fill the available space\n handle.style.contain = 'style';\n return handle;\n }\n Private.createHandle = createHandle;\n /**\n * Compute the average size of an array of box sizers.\n */\n function averageSize(sizers) {\n return sizers.reduce((v, s) => v + s.size, 0) / sizers.length || 0;\n }\n Private.averageSize = averageSize;\n /**\n * Normalize an array of values.\n */\n function normalize(values) {\n let n = values.length;\n if (n === 0) {\n return [];\n }\n let sum = values.reduce((a, b) => a + Math.abs(b), 0);\n return sum === 0 ? values.map(v => 1 / n) : values.map(v => v / sum);\n }\n Private.normalize = normalize;\n /**\n * The change handler for the attached sizing properties.\n */\n function onChildSizingChanged(child) {\n if (child.parent && child.parent.layout instanceof SplitLayout) {\n child.parent.fit();\n }\n }\n})(Private$h || (Private$h = {}));\n\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n/**\n * A layout which arranges its widgets into collapsible resizable sections.\n */\nclass AccordionLayout extends SplitLayout {\n /**\n * Construct a new accordion layout.\n *\n * @param options - The options for initializing the layout.\n *\n * #### Notes\n * The default orientation will be vertical.\n *\n * Titles must be rotated for horizontal accordion panel using CSS: see accordionpanel.css\n */\n constructor(options) {\n super({ ...options, orientation: options.orientation || 'vertical' });\n this._titles = [];\n this.titleSpace = options.titleSpace || 22;\n }\n /**\n * The section title height or width depending on the orientation.\n */\n get titleSpace() {\n return this.widgetOffset;\n }\n set titleSpace(value) {\n value = Utils$1.clampDimension(value);\n if (this.widgetOffset === value) {\n return;\n }\n this.widgetOffset = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * A read-only array of the section titles in the panel.\n */\n get titles() {\n return this._titles;\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n // Clear the layout state.\n this._titles.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n updateTitle(index, widget) {\n const oldTitle = this._titles[index];\n const expanded = oldTitle.classList.contains('lm-mod-expanded');\n const newTitle = Private$g.createTitle(this.renderer, widget.title, expanded);\n this._titles[index] = newTitle;\n // Add the title node to the parent before the widget.\n this.parent.node.replaceChild(newTitle, oldTitle);\n }\n /**\n * Insert a widget into the layout at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into the layout.\n *\n * #### Notes\n * The index will be clamped to the bounds of the widgets.\n *\n * If the widget is already added to the layout, it will be moved.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n */\n insertWidget(index, widget) {\n if (!widget.id) {\n widget.id = `id-${UUID.uuid4()}`;\n }\n super.insertWidget(index, widget);\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n */\n attachWidget(index, widget) {\n const title = Private$g.createTitle(this.renderer, widget.title);\n ArrayExt.insert(this._titles, index, title);\n // Add the title node to the parent before the widget.\n this.parent.node.appendChild(title);\n widget.node.setAttribute('role', 'region');\n widget.node.setAttribute('aria-labelledby', title.id);\n super.attachWidget(index, widget);\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n */\n moveWidget(fromIndex, toIndex, widget) {\n ArrayExt.move(this._titles, fromIndex, toIndex);\n super.moveWidget(fromIndex, toIndex, widget);\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n const title = ArrayExt.removeAt(this._titles, index);\n this.parent.node.removeChild(title);\n super.detachWidget(index, widget);\n }\n /**\n * Update the item position.\n *\n * @param i Item index\n * @param isHorizontal Whether the layout is horizontal or not\n * @param left Left position in pixels\n * @param top Top position in pixels\n * @param height Item height\n * @param width Item width\n * @param size Item size\n */\n updateItemPosition(i, isHorizontal, left, top, height, width, size) {\n const titleStyle = this._titles[i].style;\n // Titles must be rotated for horizontal accordion panel using CSS: see accordionpanel.css\n titleStyle.top = `${top}px`;\n titleStyle.left = `${left}px`;\n titleStyle.height = `${this.widgetOffset}px`;\n if (isHorizontal) {\n titleStyle.width = `${height}px`;\n }\n else {\n titleStyle.width = `${width}px`;\n }\n super.updateItemPosition(i, isHorizontal, left, top, height, width, size);\n }\n}\nvar Private$g;\n(function (Private) {\n /**\n * Create the title HTML element.\n *\n * @param renderer Accordion renderer\n * @param data Widget title\n * @returns Title HTML element\n */\n function createTitle(renderer, data, expanded = true) {\n const title = renderer.createSectionTitle(data);\n title.style.position = 'absolute';\n title.style.contain = 'strict';\n title.setAttribute('aria-label', `${data.label} Section`);\n title.setAttribute('aria-expanded', expanded ? 'true' : 'false');\n title.setAttribute('aria-controls', data.owner.id);\n if (expanded) {\n title.classList.add('lm-mod-expanded');\n }\n return title;\n }\n Private.createTitle = createTitle;\n})(Private$g || (Private$g = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A simple and convenient panel widget class.\n *\n * #### Notes\n * This class is suitable as a base class for implementing a variety of\n * convenience panel widgets, but can also be used directly with CSS to\n * arrange a collection of widgets.\n *\n * This class provides a convenience wrapper around a {@link PanelLayout}.\n */\nclass Panel extends Widget {\n /**\n * Construct a new panel.\n *\n * @param options - The options for initializing the panel.\n */\n constructor(options = {}) {\n super();\n this.addClass('lm-Panel');\n this.layout = Private$f.createLayout(options);\n }\n /**\n * A read-only array of the widgets in the panel.\n */\n get widgets() {\n return this.layout.widgets;\n }\n /**\n * Add a widget to the end of the panel.\n *\n * @param widget - The widget to add to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n addWidget(widget) {\n this.layout.addWidget(widget);\n }\n /**\n * Insert a widget at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n insertWidget(index, widget) {\n this.layout.insertWidget(index, widget);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$f;\n(function (Private) {\n /**\n * Create a panel layout for the given panel options.\n */\n function createLayout(options) {\n return options.layout || new PanelLayout();\n }\n Private.createLayout = createLayout;\n})(Private$f || (Private$f = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A panel which arranges its widgets into resizable sections.\n *\n * #### Notes\n * This class provides a convenience wrapper around a {@link SplitLayout}.\n */\nclass SplitPanel extends Panel {\n /**\n * Construct a new split panel.\n *\n * @param options - The options for initializing the split panel.\n */\n constructor(options = {}) {\n super({ layout: Private$e.createLayout(options) });\n this._handleMoved = new Signal(this);\n this._pressData = null;\n this.addClass('lm-SplitPanel');\n }\n /**\n * Dispose of the resources held by the panel.\n */\n dispose() {\n this._releaseMouse();\n super.dispose();\n }\n /**\n * Get the layout orientation for the split panel.\n */\n get orientation() {\n return this.layout.orientation;\n }\n /**\n * Set the layout orientation for the split panel.\n */\n set orientation(value) {\n this.layout.orientation = value;\n }\n /**\n * Get the content alignment for the split panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split panel.\n */\n get alignment() {\n return this.layout.alignment;\n }\n /**\n * Set the content alignment for the split panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split panel.\n */\n set alignment(value) {\n this.layout.alignment = value;\n }\n /**\n * Get the inter-element spacing for the split panel.\n */\n get spacing() {\n return this.layout.spacing;\n }\n /**\n * Set the inter-element spacing for the split panel.\n */\n set spacing(value) {\n this.layout.spacing = value;\n }\n /**\n * The renderer used by the split panel.\n */\n get renderer() {\n return this.layout.renderer;\n }\n /**\n * A signal emitted when a split handle has moved.\n */\n get handleMoved() {\n return this._handleMoved;\n }\n /**\n * A read-only array of the split handles in the panel.\n */\n get handles() {\n return this.layout.handles;\n }\n /**\n * Get the relative sizes of the widgets in the panel.\n *\n * @returns A new array of the relative sizes of the widgets.\n *\n * #### Notes\n * The returned sizes reflect the sizes of the widgets normalized\n * relative to their siblings.\n *\n * This method **does not** measure the DOM nodes.\n */\n relativeSizes() {\n return this.layout.relativeSizes();\n }\n /**\n * Set the relative sizes for the widgets in the panel.\n *\n * @param sizes - The relative sizes for the widgets in the panel.\n * @param update - Update the layout after setting relative sizes.\n * Default is True.\n *\n * #### Notes\n * Extra values are ignored, too few will yield an undefined layout.\n *\n * The actual geometry of the DOM nodes is updated asynchronously.\n */\n setRelativeSizes(sizes, update = true) {\n this.layout.setRelativeSizes(sizes, update);\n }\n /**\n * Handle the DOM events for the split panel.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the panel's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'pointerdown':\n this._evtPointerDown(event);\n break;\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('pointerdown', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('pointerdown', this);\n this._releaseMouse();\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n msg.child.addClass('lm-SplitPanel-child');\n this._releaseMouse();\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n msg.child.removeClass('lm-SplitPanel-child');\n this._releaseMouse();\n }\n /**\n * Handle the `'keydown'` event for the split panel.\n */\n _evtKeyDown(event) {\n // Stop input events during drag.\n if (this._pressData) {\n event.preventDefault();\n event.stopPropagation();\n }\n // Release the mouse if `Escape` is pressed.\n if (event.keyCode === 27) {\n this._releaseMouse();\n }\n }\n /**\n * Handle the `'pointerdown'` event for the split panel.\n */\n _evtPointerDown(event) {\n // Do nothing if the primary button is not pressed.\n if (event.button !== 0) {\n return;\n }\n // Find the handle which contains the target, if any.\n let layout = this.layout;\n let index = ArrayExt.findFirstIndex(layout.handles, handle => {\n return handle.contains(event.target);\n });\n // Bail early if the mouse press was not on a handle.\n if (index === -1) {\n return;\n }\n // Stop the event when a split handle is pressed.\n event.preventDefault();\n event.stopPropagation();\n // Add the extra document listeners.\n document.addEventListener('pointerup', this, true);\n document.addEventListener('pointermove', this, true);\n document.addEventListener('keydown', this, true);\n document.addEventListener('contextmenu', this, true);\n // Compute the offset delta for the handle press.\n let delta;\n let handle = layout.handles[index];\n let rect = handle.getBoundingClientRect();\n if (layout.orientation === 'horizontal') {\n delta = event.clientX - rect.left;\n }\n else {\n delta = event.clientY - rect.top;\n }\n // Override the cursor and store the press data.\n let style = window.getComputedStyle(handle);\n let override = Drag.overrideCursor(style.cursor);\n this._pressData = { index, delta, override };\n }\n /**\n * Handle the `'pointermove'` event for the split panel.\n */\n _evtPointerMove(event) {\n // Stop the event when dragging a split handle.\n event.preventDefault();\n event.stopPropagation();\n // Compute the desired offset position for the handle.\n let pos;\n let layout = this.layout;\n let rect = this.node.getBoundingClientRect();\n if (layout.orientation === 'horizontal') {\n pos = event.clientX - rect.left - this._pressData.delta;\n }\n else {\n pos = event.clientY - rect.top - this._pressData.delta;\n }\n // Move the handle as close to the desired position as possible.\n layout.moveHandle(this._pressData.index, pos);\n }\n /**\n * Handle the `'pointerup'` event for the split panel.\n */\n _evtPointerUp(event) {\n // Do nothing if the primary button is not released.\n if (event.button !== 0) {\n return;\n }\n // Stop the event when releasing a handle.\n event.preventDefault();\n event.stopPropagation();\n // Finalize the mouse release.\n this._releaseMouse();\n }\n /**\n * Release the mouse grab for the split panel.\n */\n _releaseMouse() {\n // Bail early if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Clear the override cursor.\n this._pressData.override.dispose();\n this._pressData = null;\n // Emit the handle moved signal.\n this._handleMoved.emit();\n // Remove the extra document listeners.\n document.removeEventListener('keydown', this, true);\n document.removeEventListener('pointerup', this, true);\n document.removeEventListener('pointermove', this, true);\n document.removeEventListener('contextmenu', this, true);\n }\n}\n/**\n * The namespace for the `SplitPanel` class statics.\n */\n(function (SplitPanel) {\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer {\n /**\n * Create a new handle for use with a split panel.\n *\n * @returns A new handle element for a split panel.\n */\n createHandle() {\n let handle = document.createElement('div');\n handle.className = 'lm-SplitPanel-handle';\n return handle;\n }\n }\n SplitPanel.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n SplitPanel.defaultRenderer = new Renderer();\n /**\n * Get the split panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The split panel stretch factor for the widget.\n */\n function getStretch(widget) {\n return SplitLayout.getStretch(widget);\n }\n SplitPanel.getStretch = getStretch;\n /**\n * Set the split panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n SplitLayout.setStretch(widget, value);\n }\n SplitPanel.setStretch = setStretch;\n})(SplitPanel || (SplitPanel = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$e;\n(function (Private) {\n /**\n * Create a split layout for the given panel options.\n */\n function createLayout(options) {\n return (options.layout ||\n new SplitLayout({\n renderer: options.renderer || SplitPanel.defaultRenderer,\n orientation: options.orientation,\n alignment: options.alignment,\n spacing: options.spacing\n }));\n }\n Private.createLayout = createLayout;\n})(Private$e || (Private$e = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A panel which arranges its widgets into resizable sections separated by a title widget.\n *\n * #### Notes\n * This class provides a convenience wrapper around {@link AccordionLayout}.\n */\nclass AccordionPanel extends SplitPanel {\n /**\n * Construct a new accordion panel.\n *\n * @param options - The options for initializing the accordion panel.\n */\n constructor(options = {}) {\n super({ ...options, layout: Private$d.createLayout(options) });\n this._widgetSizesCache = new WeakMap();\n this._expansionToggled = new Signal(this);\n this.addClass('lm-AccordionPanel');\n }\n /**\n * The renderer used by the accordion panel.\n */\n get renderer() {\n return this.layout.renderer;\n }\n /**\n * The section title space.\n *\n * This is the height if the panel is vertical and the width if it is\n * horizontal.\n */\n get titleSpace() {\n return this.layout.titleSpace;\n }\n set titleSpace(value) {\n this.layout.titleSpace = value;\n }\n /**\n * A read-only array of the section titles in the panel.\n */\n get titles() {\n return this.layout.titles;\n }\n /**\n * A signal emitted when a widget of the AccordionPanel is collapsed or expanded.\n */\n get expansionToggled() {\n return this._expansionToggled;\n }\n /**\n * Add a widget to the end of the panel.\n *\n * @param widget - The widget to add to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n addWidget(widget) {\n super.addWidget(widget);\n widget.title.changed.connect(this._onTitleChanged, this);\n }\n /**\n * Collapse the widget at position `index`.\n *\n * #### Notes\n * If no widget is found for `index`, this will bail.\n *\n * @param index Widget index\n */\n collapse(index) {\n const widget = this.layout.widgets[index];\n if (widget && !widget.isHidden) {\n this._toggleExpansion(index);\n }\n }\n /**\n * Expand the widget at position `index`.\n *\n * #### Notes\n * If no widget is found for `index`, this will bail.\n *\n * @param index Widget index\n */\n expand(index) {\n const widget = this.layout.widgets[index];\n if (widget && widget.isHidden) {\n this._toggleExpansion(index);\n }\n }\n /**\n * Insert a widget at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n insertWidget(index, widget) {\n super.insertWidget(index, widget);\n widget.title.changed.connect(this._onTitleChanged, this);\n }\n /**\n * Handle the DOM events for the accordion panel.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the panel's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n super.handleEvent(event);\n switch (event.type) {\n case 'click':\n this._evtClick(event);\n break;\n case 'keydown':\n this._eventKeyDown(event);\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('click', this);\n this.node.addEventListener('keydown', this);\n super.onBeforeAttach(msg);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n super.onAfterDetach(msg);\n this.node.removeEventListener('click', this);\n this.node.removeEventListener('keydown', this);\n }\n /**\n * Handle the `changed` signal of a title object.\n */\n _onTitleChanged(sender) {\n const index = ArrayExt.findFirstIndex(this.widgets, widget => {\n return widget.contains(sender.owner);\n });\n if (index >= 0) {\n this.layout.updateTitle(index, sender.owner);\n this.update();\n }\n }\n /**\n * Compute the size of widgets in this panel on the title click event.\n * On closing, the size of the widget is cached and we will try to expand\n * the last opened widget.\n * On opening, we will use the cached size if it is available to restore the\n * widget.\n * In both cases, if we can not compute the size of widgets, we will let\n * `SplitLayout` decide.\n *\n * @param index - The index of widget to be opened of closed\n *\n * @returns Relative size of widgets in this panel, if this size can\n * not be computed, return `undefined`\n */\n _computeWidgetSize(index) {\n const layout = this.layout;\n const widget = layout.widgets[index];\n if (!widget) {\n return undefined;\n }\n const isHidden = widget.isHidden;\n const widgetSizes = layout.absoluteSizes();\n const delta = (isHidden ? -1 : 1) * this.spacing;\n const totalSize = widgetSizes.reduce((prev, curr) => prev + curr);\n let newSize = [...widgetSizes];\n if (!isHidden) {\n // Hide the widget\n const currentSize = widgetSizes[index];\n this._widgetSizesCache.set(widget, currentSize);\n newSize[index] = 0;\n const widgetToCollapse = newSize.map(sz => sz > 0).lastIndexOf(true);\n if (widgetToCollapse === -1) {\n // All widget are closed, let the `SplitLayout` compute widget sizes.\n return undefined;\n }\n newSize[widgetToCollapse] =\n widgetSizes[widgetToCollapse] + currentSize + delta;\n }\n else {\n // Show the widget\n const previousSize = this._widgetSizesCache.get(widget);\n if (!previousSize) {\n // Previous size is unavailable, let the `SplitLayout` compute widget sizes.\n return undefined;\n }\n newSize[index] += previousSize;\n const widgetToCollapse = newSize\n .map(sz => sz - previousSize > 0)\n .lastIndexOf(true);\n if (widgetToCollapse === -1) {\n // Can not reduce the size of one widget, reduce all opened widgets\n // proportionally with its size.\n newSize.forEach((_, idx) => {\n if (idx !== index) {\n newSize[idx] -=\n (widgetSizes[idx] / totalSize) * (previousSize - delta);\n }\n });\n }\n else {\n newSize[widgetToCollapse] -= previousSize - delta;\n }\n }\n return newSize.map(sz => sz / (totalSize + delta));\n }\n /**\n * Handle the `'click'` event for the accordion panel\n */\n _evtClick(event) {\n const target = event.target;\n if (target) {\n const index = ArrayExt.findFirstIndex(this.titles, title => {\n return title.contains(target);\n });\n if (index >= 0) {\n event.preventDefault();\n event.stopPropagation();\n this._toggleExpansion(index);\n }\n }\n }\n /**\n * Handle the `'keydown'` event for the accordion panel.\n */\n _eventKeyDown(event) {\n if (event.defaultPrevented) {\n return;\n }\n const target = event.target;\n let handled = false;\n if (target) {\n const index = ArrayExt.findFirstIndex(this.titles, title => {\n return title.contains(target);\n });\n if (index >= 0) {\n const keyCode = event.keyCode.toString();\n // If Space or Enter is pressed on title, emulate click event\n if (event.key.match(/Space|Enter/) || keyCode.match(/13|32/)) {\n target.click();\n handled = true;\n }\n else if (this.orientation === 'horizontal'\n ? event.key.match(/ArrowLeft|ArrowRight/) || keyCode.match(/37|39/)\n : event.key.match(/ArrowUp|ArrowDown/) || keyCode.match(/38|40/)) {\n // If Up or Down (for vertical) / Left or Right (for horizontal) is pressed on title, loop on titles\n const direction = event.key.match(/ArrowLeft|ArrowUp/) || keyCode.match(/37|38/)\n ? -1\n : 1;\n const length = this.titles.length;\n const newIndex = (index + length + direction) % length;\n this.titles[newIndex].focus();\n handled = true;\n }\n else if (event.key === 'End' || keyCode === '35') {\n // If End is pressed on title, focus on the last title\n this.titles[this.titles.length - 1].focus();\n handled = true;\n }\n else if (event.key === 'Home' || keyCode === '36') {\n // If Home is pressed on title, focus on the first title\n this.titles[0].focus();\n handled = true;\n }\n }\n if (handled) {\n event.preventDefault();\n }\n }\n }\n _toggleExpansion(index) {\n const title = this.titles[index];\n const widget = this.layout.widgets[index];\n const newSize = this._computeWidgetSize(index);\n if (newSize) {\n this.setRelativeSizes(newSize, false);\n }\n if (widget.isHidden) {\n title.classList.add('lm-mod-expanded');\n title.setAttribute('aria-expanded', 'true');\n widget.show();\n }\n else {\n title.classList.remove('lm-mod-expanded');\n title.setAttribute('aria-expanded', 'false');\n widget.hide();\n }\n // Emit the expansion state signal.\n this._expansionToggled.emit(index);\n }\n}\n/**\n * The namespace for the `AccordionPanel` class statics.\n */\n(function (AccordionPanel) {\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer extends SplitPanel.Renderer {\n constructor() {\n super();\n /**\n * A selector which matches any title node in the accordion.\n */\n this.titleClassName = 'lm-AccordionPanel-title';\n this._titleID = 0;\n this._titleKeys = new WeakMap();\n this._uuid = ++Renderer._nInstance;\n }\n /**\n * Render the collapse indicator for a section title.\n *\n * @param data - The data to use for rendering the section title.\n *\n * @returns A element representing the collapse indicator.\n */\n createCollapseIcon(data) {\n return document.createElement('span');\n }\n /**\n * Render the element for a section title.\n *\n * @param data - The data to use for rendering the section title.\n *\n * @returns A element representing the section title.\n */\n createSectionTitle(data) {\n const handle = document.createElement('h3');\n handle.setAttribute('tabindex', '0');\n handle.id = this.createTitleKey(data);\n handle.className = this.titleClassName;\n for (const aData in data.dataset) {\n handle.dataset[aData] = data.dataset[aData];\n }\n const collapser = handle.appendChild(this.createCollapseIcon(data));\n collapser.className = 'lm-AccordionPanel-titleCollapser';\n const label = handle.appendChild(document.createElement('span'));\n label.className = 'lm-AccordionPanel-titleLabel';\n label.textContent = data.label;\n label.title = data.caption || data.label;\n return handle;\n }\n /**\n * Create a unique render key for the title.\n *\n * @param data - The data to use for the title.\n *\n * @returns The unique render key for the title.\n *\n * #### Notes\n * This method caches the key against the section title the first time\n * the key is generated.\n */\n createTitleKey(data) {\n let key = this._titleKeys.get(data);\n if (key === undefined) {\n key = `title-key-${this._uuid}-${this._titleID++}`;\n this._titleKeys.set(data, key);\n }\n return key;\n }\n }\n Renderer._nInstance = 0;\n AccordionPanel.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n AccordionPanel.defaultRenderer = new Renderer();\n})(AccordionPanel || (AccordionPanel = {}));\nvar Private$d;\n(function (Private) {\n /**\n * Create an accordion layout for the given panel options.\n *\n * @param options Panel options\n * @returns Panel layout\n */\n function createLayout(options) {\n return (options.layout ||\n new AccordionLayout({\n renderer: options.renderer || AccordionPanel.defaultRenderer,\n orientation: options.orientation,\n alignment: options.alignment,\n spacing: options.spacing,\n titleSpace: options.titleSpace\n }));\n }\n Private.createLayout = createLayout;\n})(Private$d || (Private$d = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which arranges its widgets in a single row or column.\n */\nclass BoxLayout extends PanelLayout {\n /**\n * Construct a new box layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options = {}) {\n super();\n this._fixed = 0;\n this._spacing = 4;\n this._dirty = false;\n this._sizers = [];\n this._items = [];\n this._box = null;\n this._alignment = 'start';\n this._direction = 'top-to-bottom';\n if (options.direction !== undefined) {\n this._direction = options.direction;\n }\n if (options.alignment !== undefined) {\n this._alignment = options.alignment;\n }\n if (options.spacing !== undefined) {\n this._spacing = Utils$1.clampDimension(options.spacing);\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the layout items.\n for (const item of this._items) {\n item.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n this._sizers.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Get the layout direction for the box layout.\n */\n get direction() {\n return this._direction;\n }\n /**\n * Set the layout direction for the box layout.\n */\n set direction(value) {\n if (this._direction === value) {\n return;\n }\n this._direction = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['direction'] = value;\n this.parent.fit();\n }\n /**\n * Get the content alignment for the box layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n get alignment() {\n return this._alignment;\n }\n /**\n * Set the content alignment for the box layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n set alignment(value) {\n if (this._alignment === value) {\n return;\n }\n this._alignment = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['alignment'] = value;\n this.parent.update();\n }\n /**\n * Get the inter-element spacing for the box layout.\n */\n get spacing() {\n return this._spacing;\n }\n /**\n * Set the inter-element spacing for the box layout.\n */\n set spacing(value) {\n value = Utils$1.clampDimension(value);\n if (this._spacing === value) {\n return;\n }\n this._spacing = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n this.parent.dataset['direction'] = this.direction;\n this.parent.dataset['alignment'] = this.alignment;\n super.init();\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n attachWidget(index, widget) {\n // Create and add a new layout item for the widget.\n ArrayExt.insert(this._items, index, new LayoutItem(widget));\n // Create and add a new sizer for the widget.\n ArrayExt.insert(this._sizers, index, new BoxSizer());\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Move the layout item for the widget.\n ArrayExt.move(this._items, fromIndex, toIndex);\n // Move the sizer for the widget.\n ArrayExt.move(this._sizers, fromIndex, toIndex);\n // Post an update request for the parent widget.\n this.parent.update();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n // Remove the layout item for the widget.\n let item = ArrayExt.removeAt(this._items, index);\n // Remove the sizer for the widget.\n ArrayExt.removeAt(this._sizers, index);\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Dispose of the layout item.\n item.dispose();\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Update the fixed space for the visible items.\n this._fixed = this._spacing * Math.max(0, nVisible - 1);\n // Setup the computed minimum size.\n let horz = Private$c.isHorizontal(this._direction);\n let minW = horz ? this._fixed : 0;\n let minH = horz ? 0 : this._fixed;\n // Update the sizers and computed minimum size.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item and corresponding box sizer.\n let item = this._items[i];\n let sizer = this._sizers[i];\n // If the item is hidden, it should consume zero size.\n if (item.isHidden) {\n sizer.minSize = 0;\n sizer.maxSize = 0;\n continue;\n }\n // Update the size limits for the item.\n item.fit();\n // Update the size basis and stretch factor.\n sizer.sizeHint = BoxLayout.getSizeBasis(item.widget);\n sizer.stretch = BoxLayout.getStretch(item.widget);\n // Update the sizer limits and computed min size.\n if (horz) {\n sizer.minSize = item.minWidth;\n sizer.maxSize = item.maxWidth;\n minW += item.minWidth;\n minH = Math.max(minH, item.minHeight);\n }\n else {\n sizer.minSize = item.minHeight;\n sizer.maxSize = item.maxHeight;\n minH += item.minHeight;\n minW = Math.max(minW, item.minWidth);\n }\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Bail early if there are no visible items to layout.\n if (nVisible === 0) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the layout area adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Distribute the layout space and adjust the start position.\n let delta;\n switch (this._direction) {\n case 'left-to-right':\n delta = BoxEngine.calc(this._sizers, Math.max(0, width - this._fixed));\n break;\n case 'top-to-bottom':\n delta = BoxEngine.calc(this._sizers, Math.max(0, height - this._fixed));\n break;\n case 'right-to-left':\n delta = BoxEngine.calc(this._sizers, Math.max(0, width - this._fixed));\n left += width;\n break;\n case 'bottom-to-top':\n delta = BoxEngine.calc(this._sizers, Math.max(0, height - this._fixed));\n top += height;\n break;\n default:\n throw 'unreachable';\n }\n // Setup the variables for justification and alignment offset.\n let extra = 0;\n let offset = 0;\n // Account for alignment if there is extra layout space.\n if (delta > 0) {\n switch (this._alignment) {\n case 'start':\n break;\n case 'center':\n extra = 0;\n offset = delta / 2;\n break;\n case 'end':\n extra = 0;\n offset = delta;\n break;\n case 'justify':\n extra = delta / nVisible;\n offset = 0;\n break;\n default:\n throw 'unreachable';\n }\n }\n // Layout the items using the computed box sizes.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Fetch the computed size for the widget.\n let size = this._sizers[i].size;\n // Update the widget geometry and advance the relevant edge.\n switch (this._direction) {\n case 'left-to-right':\n item.update(left + offset, top, size + extra, height);\n left += size + extra + this._spacing;\n break;\n case 'top-to-bottom':\n item.update(left, top + offset, width, size + extra);\n top += size + extra + this._spacing;\n break;\n case 'right-to-left':\n item.update(left - offset - size - extra, top, size + extra, height);\n left -= size + extra + this._spacing;\n break;\n case 'bottom-to-top':\n item.update(left, top - offset - size - extra, width, size + extra);\n top -= size + extra + this._spacing;\n break;\n default:\n throw 'unreachable';\n }\n }\n }\n}\n/**\n * The namespace for the `BoxLayout` class statics.\n */\n(function (BoxLayout) {\n /**\n * Get the box layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box layout stretch factor for the widget.\n */\n function getStretch(widget) {\n return Private$c.stretchProperty.get(widget);\n }\n BoxLayout.getStretch = getStretch;\n /**\n * Set the box layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n Private$c.stretchProperty.set(widget, value);\n }\n BoxLayout.setStretch = setStretch;\n /**\n * Get the box layout size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box layout size basis for the widget.\n */\n function getSizeBasis(widget) {\n return Private$c.sizeBasisProperty.get(widget);\n }\n BoxLayout.getSizeBasis = getSizeBasis;\n /**\n * Set the box layout size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the size basis.\n */\n function setSizeBasis(widget, value) {\n Private$c.sizeBasisProperty.set(widget, value);\n }\n BoxLayout.setSizeBasis = setSizeBasis;\n})(BoxLayout || (BoxLayout = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$c;\n(function (Private) {\n /**\n * The property descriptor for a widget stretch factor.\n */\n Private.stretchProperty = new AttachedProperty({\n name: 'stretch',\n create: () => 0,\n coerce: (owner, value) => Math.max(0, Math.floor(value)),\n changed: onChildSizingChanged\n });\n /**\n * The property descriptor for a widget size basis.\n */\n Private.sizeBasisProperty = new AttachedProperty({\n name: 'sizeBasis',\n create: () => 0,\n coerce: (owner, value) => Math.max(0, Math.floor(value)),\n changed: onChildSizingChanged\n });\n /**\n * Test whether a direction has horizontal orientation.\n */\n function isHorizontal(dir) {\n return dir === 'left-to-right' || dir === 'right-to-left';\n }\n Private.isHorizontal = isHorizontal;\n /**\n * Clamp a spacing value to an integer >= 0.\n */\n function clampSpacing(value) {\n return Math.max(0, Math.floor(value));\n }\n Private.clampSpacing = clampSpacing;\n /**\n * The change handler for the attached sizing properties.\n */\n function onChildSizingChanged(child) {\n if (child.parent && child.parent.layout instanceof BoxLayout) {\n child.parent.fit();\n }\n }\n})(Private$c || (Private$c = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A panel which arranges its widgets in a single row or column.\n *\n * #### Notes\n * This class provides a convenience wrapper around a {@link BoxLayout}.\n */\nclass BoxPanel extends Panel {\n /**\n * Construct a new box panel.\n *\n * @param options - The options for initializing the box panel.\n */\n constructor(options = {}) {\n super({ layout: Private$b.createLayout(options) });\n this.addClass('lm-BoxPanel');\n }\n /**\n * Get the layout direction for the box panel.\n */\n get direction() {\n return this.layout.direction;\n }\n /**\n * Set the layout direction for the box panel.\n */\n set direction(value) {\n this.layout.direction = value;\n }\n /**\n * Get the content alignment for the box panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n get alignment() {\n return this.layout.alignment;\n }\n /**\n * Set the content alignment for the box panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n set alignment(value) {\n this.layout.alignment = value;\n }\n /**\n * Get the inter-element spacing for the box panel.\n */\n get spacing() {\n return this.layout.spacing;\n }\n /**\n * Set the inter-element spacing for the box panel.\n */\n set spacing(value) {\n this.layout.spacing = value;\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n msg.child.addClass('lm-BoxPanel-child');\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n msg.child.removeClass('lm-BoxPanel-child');\n }\n}\n/**\n * The namespace for the `BoxPanel` class statics.\n */\n(function (BoxPanel) {\n /**\n * Get the box panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box panel stretch factor for the widget.\n */\n function getStretch(widget) {\n return BoxLayout.getStretch(widget);\n }\n BoxPanel.getStretch = getStretch;\n /**\n * Set the box panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n BoxLayout.setStretch(widget, value);\n }\n BoxPanel.setStretch = setStretch;\n /**\n * Get the box panel size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box panel size basis for the widget.\n */\n function getSizeBasis(widget) {\n return BoxLayout.getSizeBasis(widget);\n }\n BoxPanel.getSizeBasis = getSizeBasis;\n /**\n * Set the box panel size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the size basis.\n */\n function setSizeBasis(widget, value) {\n BoxLayout.setSizeBasis(widget, value);\n }\n BoxPanel.setSizeBasis = setSizeBasis;\n})(BoxPanel || (BoxPanel = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$b;\n(function (Private) {\n /**\n * Create a box layout for the given panel options.\n */\n function createLayout(options) {\n return options.layout || new BoxLayout(options);\n }\n Private.createLayout = createLayout;\n})(Private$b || (Private$b = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which displays command items as a searchable palette.\n */\nclass CommandPalette extends Widget {\n /**\n * Construct a new command palette.\n *\n * @param options - The options for initializing the palette.\n */\n constructor(options) {\n super({ node: Private$a.createNode() });\n this._activeIndex = -1;\n this._items = [];\n this._results = null;\n this.addClass('lm-CommandPalette');\n this.setFlag(Widget.Flag.DisallowLayout);\n this.commands = options.commands;\n this.renderer = options.renderer || CommandPalette.defaultRenderer;\n this.commands.commandChanged.connect(this._onGenericChange, this);\n this.commands.keyBindingChanged.connect(this._onGenericChange, this);\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n this._items.length = 0;\n this._results = null;\n super.dispose();\n }\n /**\n * The command palette search node.\n *\n * #### Notes\n * This is the node which contains the search-related elements.\n */\n get searchNode() {\n return this.node.getElementsByClassName('lm-CommandPalette-search')[0];\n }\n /**\n * The command palette input node.\n *\n * #### Notes\n * This is the actual input node for the search area.\n */\n get inputNode() {\n return this.node.getElementsByClassName('lm-CommandPalette-input')[0];\n }\n /**\n * The command palette content node.\n *\n * #### Notes\n * This is the node which holds the command item nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-CommandPalette-content')[0];\n }\n /**\n * A read-only array of the command items in the palette.\n */\n get items() {\n return this._items;\n }\n /**\n * Add a command item to the command palette.\n *\n * @param options - The options for creating the command item.\n *\n * @returns The command item added to the palette.\n */\n addItem(options) {\n // Create a new command item for the options.\n let item = Private$a.createItem(this.commands, options);\n // Add the item to the array.\n this._items.push(item);\n // Refresh the search results.\n this.refresh();\n // Return the item added to the palette.\n return item;\n }\n /**\n * Adds command items to the command palette.\n *\n * @param items - An array of options for creating each command item.\n *\n * @returns The command items added to the palette.\n */\n addItems(items) {\n const newItems = items.map(item => Private$a.createItem(this.commands, item));\n newItems.forEach(item => this._items.push(item));\n this.refresh();\n return newItems;\n }\n /**\n * Remove an item from the command palette.\n *\n * @param item - The item to remove from the palette.\n *\n * #### Notes\n * This is a no-op if the item is not in the palette.\n */\n removeItem(item) {\n this.removeItemAt(this._items.indexOf(item));\n }\n /**\n * Remove the item at a given index from the command palette.\n *\n * @param index - The index of the item to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeItemAt(index) {\n // Remove the item from the array.\n let item = ArrayExt.removeAt(this._items, index);\n // Bail if the index is out of range.\n if (!item) {\n return;\n }\n // Refresh the search results.\n this.refresh();\n }\n /**\n * Remove all items from the command palette.\n */\n clearItems() {\n // Bail if there is nothing to remove.\n if (this._items.length === 0) {\n return;\n }\n // Clear the array of items.\n this._items.length = 0;\n // Refresh the search results.\n this.refresh();\n }\n /**\n * Clear the search results and schedule an update.\n *\n * #### Notes\n * This should be called whenever the search results of the palette\n * should be updated.\n *\n * This is typically called automatically by the palette as needed,\n * but can be called manually if the input text is programatically\n * changed.\n *\n * The rendered results are updated asynchronously.\n */\n refresh() {\n this._results = null;\n if (this.inputNode.value !== '') {\n let clear = this.node.getElementsByClassName('lm-close-icon')[0];\n clear.style.display = 'inherit';\n }\n else {\n let clear = this.node.getElementsByClassName('lm-close-icon')[0];\n clear.style.display = 'none';\n }\n this.update();\n }\n /**\n * Handle the DOM events for the command palette.\n *\n * @param event - The DOM event sent to the command palette.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the command palette's DOM node.\n * It should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'click':\n this._evtClick(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'input':\n this.refresh();\n break;\n case 'focus':\n case 'blur':\n this._toggleFocused();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('click', this);\n this.node.addEventListener('keydown', this);\n this.node.addEventListener('input', this);\n this.node.addEventListener('focus', this, true);\n this.node.addEventListener('blur', this, true);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('click', this);\n this.node.removeEventListener('keydown', this);\n this.node.removeEventListener('input', this);\n this.node.removeEventListener('focus', this, true);\n this.node.removeEventListener('blur', this, true);\n }\n /**\n * A message handler invoked on an `'after-show'` message.\n */\n onAfterShow(msg) {\n this.update();\n super.onAfterShow(msg);\n }\n /**\n * A message handler invoked on an `'activate-request'` message.\n */\n onActivateRequest(msg) {\n if (this.isAttached) {\n let input = this.inputNode;\n input.focus();\n input.select();\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.isHidden) {\n return;\n }\n // Fetch the current query text and content node.\n let query = this.inputNode.value;\n let contentNode = this.contentNode;\n // Ensure the search results are generated.\n let results = this._results;\n if (!results) {\n // Generate and store the new search results.\n results = this._results = Private$a.search(this._items, query);\n // Reset the active index.\n this._activeIndex = query\n ? ArrayExt.findFirstIndex(results, Private$a.canActivate)\n : -1;\n }\n // If there is no query and no results, clear the content.\n if (!query && results.length === 0) {\n VirtualDOM.render(null, contentNode);\n return;\n }\n // If the is a query but no results, render the empty message.\n if (query && results.length === 0) {\n let content = this.renderer.renderEmptyMessage({ query });\n VirtualDOM.render(content, contentNode);\n return;\n }\n // Create the render content for the search results.\n let renderer = this.renderer;\n let activeIndex = this._activeIndex;\n let content = new Array(results.length);\n for (let i = 0, n = results.length; i < n; ++i) {\n let result = results[i];\n if (result.type === 'header') {\n let indices = result.indices;\n let category = result.category;\n content[i] = renderer.renderHeader({ category, indices });\n }\n else {\n let item = result.item;\n let indices = result.indices;\n let active = i === activeIndex;\n content[i] = renderer.renderItem({ item, indices, active });\n }\n }\n // Render the search result content.\n VirtualDOM.render(content, contentNode);\n // Adjust the scroll position as needed.\n if (activeIndex < 0 || activeIndex >= results.length) {\n contentNode.scrollTop = 0;\n }\n else {\n let element = contentNode.children[activeIndex];\n ElementExt.scrollIntoViewIfNeeded(contentNode, element);\n }\n }\n /**\n * Handle the `'click'` event for the command palette.\n */\n _evtClick(event) {\n // Bail if the click is not the left button.\n if (event.button !== 0) {\n return;\n }\n // Clear input if the target is clear button\n if (event.target.classList.contains('lm-close-icon')) {\n this.inputNode.value = '';\n this.refresh();\n return;\n }\n // Find the index of the item which was clicked.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return node.contains(event.target);\n });\n // Bail if the click was not on an item.\n if (index === -1) {\n return;\n }\n // Kill the event when a content item is clicked.\n event.preventDefault();\n event.stopPropagation();\n // Execute the item if possible.\n this._execute(index);\n }\n /**\n * Handle the `'keydown'` event for the command palette.\n */\n _evtKeyDown(event) {\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n switch (event.keyCode) {\n case 13: // Enter\n event.preventDefault();\n event.stopPropagation();\n this._execute(this._activeIndex);\n break;\n case 38: // Up Arrow\n event.preventDefault();\n event.stopPropagation();\n this._activatePreviousItem();\n break;\n case 40: // Down Arrow\n event.preventDefault();\n event.stopPropagation();\n this._activateNextItem();\n break;\n }\n }\n /**\n * Activate the next enabled command item.\n */\n _activateNextItem() {\n // Bail if there are no search results.\n if (!this._results || this._results.length === 0) {\n return;\n }\n // Find the next enabled item index.\n let ai = this._activeIndex;\n let n = this._results.length;\n let start = ai < n - 1 ? ai + 1 : 0;\n let stop = start === 0 ? n - 1 : start - 1;\n this._activeIndex = ArrayExt.findFirstIndex(this._results, Private$a.canActivate, start, stop);\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Activate the previous enabled command item.\n */\n _activatePreviousItem() {\n // Bail if there are no search results.\n if (!this._results || this._results.length === 0) {\n return;\n }\n // Find the previous enabled item index.\n let ai = this._activeIndex;\n let n = this._results.length;\n let start = ai <= 0 ? n - 1 : ai - 1;\n let stop = start === n - 1 ? 0 : start + 1;\n this._activeIndex = ArrayExt.findLastIndex(this._results, Private$a.canActivate, start, stop);\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Execute the command item at the given index, if possible.\n */\n _execute(index) {\n // Bail if there are no search results.\n if (!this._results) {\n return;\n }\n // Bail if the index is out of range.\n let part = this._results[index];\n if (!part) {\n return;\n }\n // Update the search text if the item is a header.\n if (part.type === 'header') {\n let input = this.inputNode;\n input.value = `${part.category.toLowerCase()} `;\n input.focus();\n this.refresh();\n return;\n }\n // Bail if item is not enabled.\n if (!part.item.isEnabled) {\n return;\n }\n // Execute the item.\n this.commands.execute(part.item.command, part.item.args);\n // Clear the query text.\n this.inputNode.value = '';\n // Refresh the search results.\n this.refresh();\n }\n /**\n * Toggle the focused modifier based on the input node focus state.\n */\n _toggleFocused() {\n let focused = document.activeElement === this.inputNode;\n this.toggleClass('lm-mod-focused', focused);\n }\n /**\n * A signal handler for generic command changes.\n */\n _onGenericChange() {\n this.refresh();\n }\n}\n/**\n * The namespace for the `CommandPalette` class statics.\n */\n(function (CommandPalette) {\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer {\n /**\n * Render the virtual element for a command palette header.\n *\n * @param data - The data to use for rendering the header.\n *\n * @returns A virtual element representing the header.\n */\n renderHeader(data) {\n let content = this.formatHeader(data);\n return h.li({ className: 'lm-CommandPalette-header' }, content);\n }\n /**\n * Render the virtual element for a command palette item.\n *\n * @param data - The data to use for rendering the item.\n *\n * @returns A virtual element representing the item.\n */\n renderItem(data) {\n let className = this.createItemClass(data);\n let dataset = this.createItemDataset(data);\n if (data.item.isToggleable) {\n return h.li({\n className,\n dataset,\n role: 'menuitemcheckbox',\n 'aria-checked': `${data.item.isToggled}`\n }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data));\n }\n return h.li({\n className,\n dataset,\n role: 'menuitem'\n }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data));\n }\n /**\n * Render the empty results message for a command palette.\n *\n * @param data - The data to use for rendering the message.\n *\n * @returns A virtual element representing the message.\n */\n renderEmptyMessage(data) {\n let content = this.formatEmptyMessage(data);\n return h.li({ className: 'lm-CommandPalette-emptyMessage' }, content);\n }\n /**\n * Render the icon for a command palette item.\n *\n * @param data - The data to use for rendering the icon.\n *\n * @returns A virtual element representing the icon.\n */\n renderItemIcon(data) {\n let className = this.createIconClass(data);\n // If data.item.icon is undefined, it will be ignored.\n return h.div({ className }, data.item.icon, data.item.iconLabel);\n }\n /**\n * Render the content for a command palette item.\n *\n * @param data - The data to use for rendering the content.\n *\n * @returns A virtual element representing the content.\n */\n renderItemContent(data) {\n return h.div({ className: 'lm-CommandPalette-itemContent' }, this.renderItemLabel(data), this.renderItemCaption(data));\n }\n /**\n * Render the label for a command palette item.\n *\n * @param data - The data to use for rendering the label.\n *\n * @returns A virtual element representing the label.\n */\n renderItemLabel(data) {\n let content = this.formatItemLabel(data);\n return h.div({ className: 'lm-CommandPalette-itemLabel' }, content);\n }\n /**\n * Render the caption for a command palette item.\n *\n * @param data - The data to use for rendering the caption.\n *\n * @returns A virtual element representing the caption.\n */\n renderItemCaption(data) {\n let content = this.formatItemCaption(data);\n return h.div({ className: 'lm-CommandPalette-itemCaption' }, content);\n }\n /**\n * Render the shortcut for a command palette item.\n *\n * @param data - The data to use for rendering the shortcut.\n *\n * @returns A virtual element representing the shortcut.\n */\n renderItemShortcut(data) {\n let content = this.formatItemShortcut(data);\n return h.div({ className: 'lm-CommandPalette-itemShortcut' }, content);\n }\n /**\n * Create the class name for the command palette item.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the command palette item.\n */\n createItemClass(data) {\n // Set up the initial class name.\n let name = 'lm-CommandPalette-item';\n // Add the boolean state classes.\n if (!data.item.isEnabled) {\n name += ' lm-mod-disabled';\n }\n if (data.item.isToggled) {\n name += ' lm-mod-toggled';\n }\n if (data.active) {\n name += ' lm-mod-active';\n }\n // Add the extra class.\n let extra = data.item.className;\n if (extra) {\n name += ` ${extra}`;\n }\n // Return the complete class name.\n return name;\n }\n /**\n * Create the dataset for the command palette item.\n *\n * @param data - The data to use for creating the dataset.\n *\n * @returns The dataset for the command palette item.\n */\n createItemDataset(data) {\n return { ...data.item.dataset, command: data.item.command };\n }\n /**\n * Create the class name for the command item icon.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the item icon.\n */\n createIconClass(data) {\n let name = 'lm-CommandPalette-itemIcon';\n let extra = data.item.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n /**\n * Create the render content for the header node.\n *\n * @param data - The data to use for the header content.\n *\n * @returns The content to add to the header node.\n */\n formatHeader(data) {\n if (!data.indices || data.indices.length === 0) {\n return data.category;\n }\n return StringExt.highlight(data.category, data.indices, h.mark);\n }\n /**\n * Create the render content for the empty message node.\n *\n * @param data - The data to use for the empty message content.\n *\n * @returns The content to add to the empty message node.\n */\n formatEmptyMessage(data) {\n return `No commands found that match '${data.query}'`;\n }\n /**\n * Create the render content for the item shortcut node.\n *\n * @param data - The data to use for the shortcut content.\n *\n * @returns The content to add to the shortcut node.\n */\n formatItemShortcut(data) {\n let kb = data.item.keyBinding;\n return kb ? CommandRegistry.formatKeystroke(kb.keys) : null;\n }\n /**\n * Create the render content for the item label node.\n *\n * @param data - The data to use for the label content.\n *\n * @returns The content to add to the label node.\n */\n formatItemLabel(data) {\n if (!data.indices || data.indices.length === 0) {\n return data.item.label;\n }\n return StringExt.highlight(data.item.label, data.indices, h.mark);\n }\n /**\n * Create the render content for the item caption node.\n *\n * @param data - The data to use for the caption content.\n *\n * @returns The content to add to the caption node.\n */\n formatItemCaption(data) {\n return data.item.caption;\n }\n }\n CommandPalette.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n CommandPalette.defaultRenderer = new Renderer();\n})(CommandPalette || (CommandPalette = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$a;\n(function (Private) {\n /**\n * Create the DOM node for a command palette.\n */\n function createNode() {\n let node = document.createElement('div');\n let search = document.createElement('div');\n let wrapper = document.createElement('div');\n let input = document.createElement('input');\n let content = document.createElement('ul');\n let clear = document.createElement('button');\n search.className = 'lm-CommandPalette-search';\n wrapper.className = 'lm-CommandPalette-wrapper';\n input.className = 'lm-CommandPalette-input';\n clear.className = 'lm-close-icon';\n content.className = 'lm-CommandPalette-content';\n content.setAttribute('role', 'menu');\n input.spellcheck = false;\n wrapper.appendChild(input);\n wrapper.appendChild(clear);\n search.appendChild(wrapper);\n node.appendChild(search);\n node.appendChild(content);\n return node;\n }\n Private.createNode = createNode;\n /**\n * Create a new command item from a command registry and options.\n */\n function createItem(commands, options) {\n return new CommandItem(commands, options);\n }\n Private.createItem = createItem;\n /**\n * Search an array of command items for fuzzy matches.\n */\n function search(items, query) {\n // Fuzzy match the items for the query.\n let scores = matchItems(items, query);\n // Sort the items based on their score.\n scores.sort(scoreCmp);\n // Create the results for the search.\n return createResults(scores);\n }\n Private.search = search;\n /**\n * Test whether a result item can be activated.\n */\n function canActivate(result) {\n return result.type === 'item' && result.item.isEnabled;\n }\n Private.canActivate = canActivate;\n /**\n * Normalize a category for a command item.\n */\n function normalizeCategory(category) {\n return category.trim().replace(/\\s+/g, ' ');\n }\n /**\n * Normalize the query text for a fuzzy search.\n */\n function normalizeQuery(text) {\n return text.replace(/\\s+/g, '').toLowerCase();\n }\n /**\n * Perform a fuzzy match on an array of command items.\n */\n function matchItems(items, query) {\n // Normalize the query text to lower case with no whitespace.\n query = normalizeQuery(query);\n // Create the array to hold the scores.\n let scores = [];\n // Iterate over the items and match against the query.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Ignore items which are not visible.\n let item = items[i];\n if (!item.isVisible) {\n continue;\n }\n // If the query is empty, all items are matched by default.\n if (!query) {\n scores.push({\n matchType: 3 /* MatchType.Default */,\n categoryIndices: null,\n labelIndices: null,\n score: 0,\n item\n });\n continue;\n }\n // Run the fuzzy search for the item and query.\n let score = fuzzySearch(item, query);\n // Ignore the item if it is not a match.\n if (!score) {\n continue;\n }\n // Penalize disabled items.\n // TODO - push disabled items all the way down in sort cmp?\n if (!item.isEnabled) {\n score.score += 1000;\n }\n // Add the score to the results.\n scores.push(score);\n }\n // Return the final array of scores.\n return scores;\n }\n /**\n * Perform a fuzzy search on a single command item.\n */\n function fuzzySearch(item, query) {\n // Create the source text to be searched.\n let category = item.category.toLowerCase();\n let label = item.label.toLowerCase();\n let source = `${category} ${label}`;\n // Set up the match score and indices array.\n let score = Infinity;\n let indices = null;\n // The regex for search word boundaries\n let rgx = /\\b\\w/g;\n // Search the source by word boundary.\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // Find the next word boundary in the source.\n let rgxMatch = rgx.exec(source);\n // Break if there is no more source context.\n if (!rgxMatch) {\n break;\n }\n // Run the string match on the relevant substring.\n let match = StringExt.matchSumOfDeltas(source, query, rgxMatch.index);\n // Break if there is no match.\n if (!match) {\n break;\n }\n // Update the match if the score is better.\n if (match.score <= score) {\n score = match.score;\n indices = match.indices;\n }\n }\n // Bail if there was no match.\n if (!indices || score === Infinity) {\n return null;\n }\n // Compute the pivot index between category and label text.\n let pivot = category.length + 1;\n // Find the slice index to separate matched indices.\n let j = ArrayExt.lowerBound(indices, pivot, (a, b) => a - b);\n // Extract the matched category and label indices.\n let categoryIndices = indices.slice(0, j);\n let labelIndices = indices.slice(j);\n // Adjust the label indices for the pivot offset.\n for (let i = 0, n = labelIndices.length; i < n; ++i) {\n labelIndices[i] -= pivot;\n }\n // Handle a pure label match.\n if (categoryIndices.length === 0) {\n return {\n matchType: 0 /* MatchType.Label */,\n categoryIndices: null,\n labelIndices,\n score,\n item\n };\n }\n // Handle a pure category match.\n if (labelIndices.length === 0) {\n return {\n matchType: 1 /* MatchType.Category */,\n categoryIndices,\n labelIndices: null,\n score,\n item\n };\n }\n // Handle a split match.\n return {\n matchType: 2 /* MatchType.Split */,\n categoryIndices,\n labelIndices,\n score,\n item\n };\n }\n /**\n * A sort comparison function for a match score.\n */\n function scoreCmp(a, b) {\n // First compare based on the match type\n let m1 = a.matchType - b.matchType;\n if (m1 !== 0) {\n return m1;\n }\n // Otherwise, compare based on the match score.\n let d1 = a.score - b.score;\n if (d1 !== 0) {\n return d1;\n }\n // Find the match index based on the match type.\n let i1 = 0;\n let i2 = 0;\n switch (a.matchType) {\n case 0 /* MatchType.Label */:\n i1 = a.labelIndices[0];\n i2 = b.labelIndices[0];\n break;\n case 1 /* MatchType.Category */:\n case 2 /* MatchType.Split */:\n i1 = a.categoryIndices[0];\n i2 = b.categoryIndices[0];\n break;\n }\n // Compare based on the match index.\n if (i1 !== i2) {\n return i1 - i2;\n }\n // Otherwise, compare by category.\n let d2 = a.item.category.localeCompare(b.item.category);\n if (d2 !== 0) {\n return d2;\n }\n // Otherwise, compare by rank.\n let r1 = a.item.rank;\n let r2 = b.item.rank;\n if (r1 !== r2) {\n return r1 < r2 ? -1 : 1; // Infinity safe\n }\n // Finally, compare by label.\n return a.item.label.localeCompare(b.item.label);\n }\n /**\n * Create the results from an array of sorted scores.\n */\n function createResults(scores) {\n // Set up an array to track which scores have been visited.\n let visited = new Array(scores.length);\n ArrayExt.fill(visited, false);\n // Set up the search results array.\n let results = [];\n // Iterate over each score in the array.\n for (let i = 0, n = scores.length; i < n; ++i) {\n // Ignore a score which has already been processed.\n if (visited[i]) {\n continue;\n }\n // Extract the current item and indices.\n let { item, categoryIndices } = scores[i];\n // Extract the category for the current item.\n let category = item.category;\n // Add the header result for the category.\n results.push({ type: 'header', category, indices: categoryIndices });\n // Find the rest of the scores with the same category.\n for (let j = i; j < n; ++j) {\n // Ignore a score which has already been processed.\n if (visited[j]) {\n continue;\n }\n // Extract the data for the current score.\n let { item, labelIndices } = scores[j];\n // Ignore an item with a different category.\n if (item.category !== category) {\n continue;\n }\n // Create the item result for the score.\n results.push({ type: 'item', item, indices: labelIndices });\n // Mark the score as processed.\n visited[j] = true;\n }\n }\n // Return the final results.\n return results;\n }\n /**\n * A concrete implementation of `CommandPalette.IItem`.\n */\n class CommandItem {\n /**\n * Construct a new command item.\n */\n constructor(commands, options) {\n this._commands = commands;\n this.category = normalizeCategory(options.category);\n this.command = options.command;\n this.args = options.args || JSONExt.emptyObject;\n this.rank = options.rank !== undefined ? options.rank : Infinity;\n }\n /**\n * The display label for the command item.\n */\n get label() {\n return this._commands.label(this.command, this.args);\n }\n /**\n * The icon renderer for the command item.\n */\n get icon() {\n return this._commands.icon(this.command, this.args);\n }\n /**\n * The icon class for the command item.\n */\n get iconClass() {\n return this._commands.iconClass(this.command, this.args);\n }\n /**\n * The icon label for the command item.\n */\n get iconLabel() {\n return this._commands.iconLabel(this.command, this.args);\n }\n /**\n * The display caption for the command item.\n */\n get caption() {\n return this._commands.caption(this.command, this.args);\n }\n /**\n * The extra class name for the command item.\n */\n get className() {\n return this._commands.className(this.command, this.args);\n }\n /**\n * The dataset for the command item.\n */\n get dataset() {\n return this._commands.dataset(this.command, this.args);\n }\n /**\n * Whether the command item is enabled.\n */\n get isEnabled() {\n return this._commands.isEnabled(this.command, this.args);\n }\n /**\n * Whether the command item is toggled.\n */\n get isToggled() {\n return this._commands.isToggled(this.command, this.args);\n }\n /**\n * Whether the command item is toggleable.\n */\n get isToggleable() {\n return this._commands.isToggleable(this.command, this.args);\n }\n /**\n * Whether the command item is visible.\n */\n get isVisible() {\n return this._commands.isVisible(this.command, this.args);\n }\n /**\n * The key binding for the command item.\n */\n get keyBinding() {\n let { command, args } = this;\n return (ArrayExt.findLastValue(this._commands.keyBindings, kb => {\n return kb.command === command && JSONExt.deepEqual(kb.args, args);\n }) || null);\n }\n }\n})(Private$a || (Private$a = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which displays items as a canonical menu.\n */\nclass Menu extends Widget {\n /**\n * Construct a new menu.\n *\n * @param options - The options for initializing the menu.\n */\n constructor(options) {\n super({ node: Private$9.createNode() });\n this._childIndex = -1;\n this._activeIndex = -1;\n this._openTimerID = 0;\n this._closeTimerID = 0;\n this._items = [];\n this._childMenu = null;\n this._parentMenu = null;\n this._aboutToClose = new Signal(this);\n this._menuRequested = new Signal(this);\n this.addClass('lm-Menu');\n this.setFlag(Widget.Flag.DisallowLayout);\n this.commands = options.commands;\n this.renderer = options.renderer || Menu.defaultRenderer;\n }\n /**\n * Dispose of the resources held by the menu.\n */\n dispose() {\n this.close();\n this._items.length = 0;\n super.dispose();\n }\n /**\n * A signal emitted just before the menu is closed.\n *\n * #### Notes\n * This signal is emitted when the menu receives a `'close-request'`\n * message, just before it removes itself from the DOM.\n *\n * This signal is not emitted if the menu is already detached from\n * the DOM when it receives the `'close-request'` message.\n */\n get aboutToClose() {\n return this._aboutToClose;\n }\n /**\n * A signal emitted when a new menu is requested by the user.\n *\n * #### Notes\n * This signal is emitted whenever the user presses the right or left\n * arrow keys, and a submenu cannot be opened or closed in response.\n *\n * This signal is useful when implementing menu bars in order to open\n * the next or previous menu in response to a user key press.\n *\n * This signal is only emitted for the root menu in a hierarchy.\n */\n get menuRequested() {\n return this._menuRequested;\n }\n /**\n * The parent menu of the menu.\n *\n * #### Notes\n * This is `null` unless the menu is an open submenu.\n */\n get parentMenu() {\n return this._parentMenu;\n }\n /**\n * The child menu of the menu.\n *\n * #### Notes\n * This is `null` unless the menu has an open submenu.\n */\n get childMenu() {\n return this._childMenu;\n }\n /**\n * The root menu of the menu hierarchy.\n */\n get rootMenu() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let menu = this;\n while (menu._parentMenu) {\n menu = menu._parentMenu;\n }\n return menu;\n }\n /**\n * The leaf menu of the menu hierarchy.\n */\n get leafMenu() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let menu = this;\n while (menu._childMenu) {\n menu = menu._childMenu;\n }\n return menu;\n }\n /**\n * The menu content node.\n *\n * #### Notes\n * This is the node which holds the menu item nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-Menu-content')[0];\n }\n /**\n * Get the currently active menu item.\n */\n get activeItem() {\n return this._items[this._activeIndex] || null;\n }\n /**\n * Set the currently active menu item.\n *\n * #### Notes\n * If the item cannot be activated, the item will be set to `null`.\n */\n set activeItem(value) {\n this.activeIndex = value ? this._items.indexOf(value) : -1;\n }\n /**\n * Get the index of the currently active menu item.\n *\n * #### Notes\n * This will be `-1` if no menu item is active.\n */\n get activeIndex() {\n return this._activeIndex;\n }\n /**\n * Set the index of the currently active menu item.\n *\n * #### Notes\n * If the item cannot be activated, the index will be set to `-1`.\n */\n set activeIndex(value) {\n // Adjust the value for an out of range index.\n if (value < 0 || value >= this._items.length) {\n value = -1;\n }\n // Ensure the item can be activated.\n if (value !== -1 && !Private$9.canActivate(this._items[value])) {\n value = -1;\n }\n // Bail if the index will not change.\n if (this._activeIndex === value) {\n return;\n }\n // Update the active index.\n this._activeIndex = value;\n // Make active element in focus\n if (this._activeIndex >= 0 &&\n this.contentNode.childNodes[this._activeIndex]) {\n this.contentNode.childNodes[this._activeIndex].focus();\n }\n // schedule an update of the items.\n this.update();\n }\n /**\n * A read-only array of the menu items in the menu.\n */\n get items() {\n return this._items;\n }\n /**\n * Activate the next selectable item in the menu.\n *\n * #### Notes\n * If no item is selectable, the index will be set to `-1`.\n */\n activateNextItem() {\n let n = this._items.length;\n let ai = this._activeIndex;\n let start = ai < n - 1 ? ai + 1 : 0;\n let stop = start === 0 ? n - 1 : start - 1;\n this.activeIndex = ArrayExt.findFirstIndex(this._items, Private$9.canActivate, start, stop);\n }\n /**\n * Activate the previous selectable item in the menu.\n *\n * #### Notes\n * If no item is selectable, the index will be set to `-1`.\n */\n activatePreviousItem() {\n let n = this._items.length;\n let ai = this._activeIndex;\n let start = ai <= 0 ? n - 1 : ai - 1;\n let stop = start === n - 1 ? 0 : start + 1;\n this.activeIndex = ArrayExt.findLastIndex(this._items, Private$9.canActivate, start, stop);\n }\n /**\n * Trigger the active menu item.\n *\n * #### Notes\n * If the active item is a submenu, it will be opened and the first\n * item will be activated.\n *\n * If the active item is a command, the command will be executed.\n *\n * If the menu is not attached, this is a no-op.\n *\n * If there is no active item, this is a no-op.\n */\n triggerActiveItem() {\n // Bail if the menu is not attached.\n if (!this.isAttached) {\n return;\n }\n // Bail if there is no active item.\n let item = this.activeItem;\n if (!item) {\n return;\n }\n // Cancel the pending timers.\n this._cancelOpenTimer();\n this._cancelCloseTimer();\n // If the item is a submenu, open it.\n if (item.type === 'submenu') {\n this._openChildMenu(true);\n return;\n }\n // Close the root menu before executing the command.\n this.rootMenu.close();\n // Execute the command for the item.\n let { command, args } = item;\n if (this.commands.isEnabled(command, args)) {\n this.commands.execute(command, args);\n }\n else {\n console.log(`Command '${command}' is disabled.`);\n }\n }\n /**\n * Add a menu item to the end of the menu.\n *\n * @param options - The options for creating the menu item.\n *\n * @returns The menu item added to the menu.\n */\n addItem(options) {\n return this.insertItem(this._items.length, options);\n }\n /**\n * Insert a menu item into the menu at the specified index.\n *\n * @param index - The index at which to insert the item.\n *\n * @param options - The options for creating the menu item.\n *\n * @returns The menu item added to the menu.\n *\n * #### Notes\n * The index will be clamped to the bounds of the items.\n */\n insertItem(index, options) {\n // Close the menu if it's attached.\n if (this.isAttached) {\n this.close();\n }\n // Reset the active index.\n this.activeIndex = -1;\n // Clamp the insert index to the array bounds.\n let i = Math.max(0, Math.min(index, this._items.length));\n // Create the item for the options.\n let item = Private$9.createItem(this, options);\n // Insert the item into the array.\n ArrayExt.insert(this._items, i, item);\n // Schedule an update of the items.\n this.update();\n // Return the item added to the menu.\n return item;\n }\n /**\n * Remove an item from the menu.\n *\n * @param item - The item to remove from the menu.\n *\n * #### Notes\n * This is a no-op if the item is not in the menu.\n */\n removeItem(item) {\n this.removeItemAt(this._items.indexOf(item));\n }\n /**\n * Remove the item at a given index from the menu.\n *\n * @param index - The index of the item to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeItemAt(index) {\n // Close the menu if it's attached.\n if (this.isAttached) {\n this.close();\n }\n // Reset the active index.\n this.activeIndex = -1;\n // Remove the item from the array.\n let item = ArrayExt.removeAt(this._items, index);\n // Bail if the index is out of range.\n if (!item) {\n return;\n }\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Remove all menu items from the menu.\n */\n clearItems() {\n // Close the menu if it's attached.\n if (this.isAttached) {\n this.close();\n }\n // Reset the active index.\n this.activeIndex = -1;\n // Bail if there is nothing to remove.\n if (this._items.length === 0) {\n return;\n }\n // Clear the items.\n this._items.length = 0;\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Open the menu at the specified location.\n *\n * @param x - The client X coordinate of the menu location.\n *\n * @param y - The client Y coordinate of the menu location.\n *\n * @param options - The additional options for opening the menu.\n *\n * #### Notes\n * The menu will be opened at the given location unless it will not\n * fully fit on the screen. If it will not fit, it will be adjusted\n * to fit naturally on the screen.\n *\n * This is a no-op if the menu is already attached to the DOM.\n */\n open(x, y, options = {}) {\n // Bail early if the menu is already attached.\n if (this.isAttached) {\n return;\n }\n // Extract the position options.\n let forceX = options.forceX || false;\n let forceY = options.forceY || false;\n // Open the menu as a root menu.\n Private$9.openRootMenu(this, x, y, forceX, forceY);\n // Activate the menu to accept keyboard input.\n this.activate();\n }\n /**\n * Handle the DOM events for the menu.\n *\n * @param event - The DOM event sent to the menu.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the menu's DOM nodes. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'mouseup':\n this._evtMouseUp(event);\n break;\n case 'mousemove':\n this._evtMouseMove(event);\n break;\n case 'mouseenter':\n this._evtMouseEnter(event);\n break;\n case 'mouseleave':\n this._evtMouseLeave(event);\n break;\n case 'mousedown':\n this._evtMouseDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('keydown', this);\n this.node.addEventListener('mouseup', this);\n this.node.addEventListener('mousemove', this);\n this.node.addEventListener('mouseenter', this);\n this.node.addEventListener('mouseleave', this);\n this.node.addEventListener('contextmenu', this);\n document.addEventListener('mousedown', this, true);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('keydown', this);\n this.node.removeEventListener('mouseup', this);\n this.node.removeEventListener('mousemove', this);\n this.node.removeEventListener('mouseenter', this);\n this.node.removeEventListener('mouseleave', this);\n this.node.removeEventListener('contextmenu', this);\n document.removeEventListener('mousedown', this, true);\n }\n /**\n * A message handler invoked on an `'activate-request'` message.\n */\n onActivateRequest(msg) {\n if (this.isAttached) {\n this.node.focus();\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n let items = this._items;\n let renderer = this.renderer;\n let activeIndex = this._activeIndex;\n let collapsedFlags = Private$9.computeCollapsed(items);\n let content = new Array(items.length);\n for (let i = 0, n = items.length; i < n; ++i) {\n let item = items[i];\n let active = i === activeIndex;\n let collapsed = collapsedFlags[i];\n content[i] = renderer.renderItem({\n item,\n active,\n collapsed,\n onfocus: () => {\n this.activeIndex = i;\n }\n });\n }\n VirtualDOM.render(content, this.contentNode);\n }\n /**\n * A message handler invoked on a `'close-request'` message.\n */\n onCloseRequest(msg) {\n // Cancel the pending timers.\n this._cancelOpenTimer();\n this._cancelCloseTimer();\n // Reset the active index.\n this.activeIndex = -1;\n // Close any open child menu.\n let childMenu = this._childMenu;\n if (childMenu) {\n this._childIndex = -1;\n this._childMenu = null;\n childMenu._parentMenu = null;\n childMenu.close();\n }\n // Remove this menu from its parent and activate the parent.\n let parentMenu = this._parentMenu;\n if (parentMenu) {\n this._parentMenu = null;\n parentMenu._childIndex = -1;\n parentMenu._childMenu = null;\n parentMenu.activate();\n }\n // Emit the `aboutToClose` signal if the menu is attached.\n if (this.isAttached) {\n this._aboutToClose.emit(undefined);\n }\n // Finish closing the menu.\n super.onCloseRequest(msg);\n }\n /**\n * Handle the `'keydown'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtKeyDown(event) {\n // A menu handles all keydown events.\n event.preventDefault();\n event.stopPropagation();\n // Fetch the key code for the event.\n let kc = event.keyCode;\n // Enter\n if (kc === 13) {\n this.triggerActiveItem();\n return;\n }\n // Escape\n if (kc === 27) {\n this.close();\n return;\n }\n // Left Arrow\n if (kc === 37) {\n if (this._parentMenu) {\n this.close();\n }\n else {\n this._menuRequested.emit('previous');\n }\n return;\n }\n // Up Arrow\n if (kc === 38) {\n this.activatePreviousItem();\n return;\n }\n // Right Arrow\n if (kc === 39) {\n let item = this.activeItem;\n if (item && item.type === 'submenu') {\n this.triggerActiveItem();\n }\n else {\n this.rootMenu._menuRequested.emit('next');\n }\n return;\n }\n // Down Arrow\n if (kc === 40) {\n this.activateNextItem();\n return;\n }\n // Get the pressed key character.\n let key = getKeyboardLayout().keyForKeydownEvent(event);\n // Bail if the key is not valid.\n if (!key) {\n return;\n }\n // Search for the next best matching mnemonic item.\n let start = this._activeIndex + 1;\n let result = Private$9.findMnemonic(this._items, key, start);\n // Handle the requested mnemonic based on the search results.\n // If exactly one mnemonic is matched, that item is triggered.\n // Otherwise, the next mnemonic is activated if available,\n // followed by the auto mnemonic if available.\n if (result.index !== -1 && !result.multiple) {\n this.activeIndex = result.index;\n this.triggerActiveItem();\n }\n else if (result.index !== -1) {\n this.activeIndex = result.index;\n }\n else if (result.auto !== -1) {\n this.activeIndex = result.auto;\n }\n }\n /**\n * Handle the `'mouseup'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseUp(event) {\n if (event.button !== 0) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n this.triggerActiveItem();\n }\n /**\n * Handle the `'mousemove'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseMove(event) {\n // Hit test the item nodes for the item under the mouse.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return ElementExt.hitTest(node, event.clientX, event.clientY);\n });\n // Bail early if the mouse is already over the active index.\n if (index === this._activeIndex) {\n return;\n }\n // Update and coerce the active index.\n this.activeIndex = index;\n index = this.activeIndex;\n // If the index is the current child index, cancel the timers.\n if (index === this._childIndex) {\n this._cancelOpenTimer();\n this._cancelCloseTimer();\n return;\n }\n // If a child menu is currently open, start the close timer.\n if (this._childIndex !== -1) {\n this._startCloseTimer();\n }\n // Cancel the open timer to give a full delay for opening.\n this._cancelOpenTimer();\n // Bail if the active item is not a valid submenu item.\n let item = this.activeItem;\n if (!item || item.type !== 'submenu' || !item.submenu) {\n return;\n }\n // Start the open timer to open the active item submenu.\n this._startOpenTimer();\n }\n /**\n * Handle the `'mouseenter'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseEnter(event) {\n // Synchronize the active ancestor items.\n for (let menu = this._parentMenu; menu; menu = menu._parentMenu) {\n menu._cancelOpenTimer();\n menu._cancelCloseTimer();\n menu.activeIndex = menu._childIndex;\n }\n }\n /**\n * Handle the `'mouseleave'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseLeave(event) {\n // Cancel any pending submenu opening.\n this._cancelOpenTimer();\n // If there is no open child menu, just reset the active index.\n if (!this._childMenu) {\n this.activeIndex = -1;\n return;\n }\n // If the mouse is over the child menu, cancel the close timer.\n let { clientX, clientY } = event;\n if (ElementExt.hitTest(this._childMenu.node, clientX, clientY)) {\n this._cancelCloseTimer();\n return;\n }\n // Otherwise, reset the active index and start the close timer.\n this.activeIndex = -1;\n this._startCloseTimer();\n }\n /**\n * Handle the `'mousedown'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the document node.\n */\n _evtMouseDown(event) {\n // Bail if the menu is not a root menu.\n if (this._parentMenu) {\n return;\n }\n // The mouse button which is pressed is irrelevant. If the press\n // is not on a menu, the entire hierarchy is closed and the event\n // is allowed to propagate. This allows other code to act on the\n // event, such as focusing the clicked element.\n if (Private$9.hitTestMenus(this, event.clientX, event.clientY)) {\n event.preventDefault();\n event.stopPropagation();\n }\n else {\n this.close();\n }\n }\n /**\n * Open the child menu at the active index immediately.\n *\n * If a different child menu is already open, it will be closed,\n * even if the active item is not a valid submenu.\n */\n _openChildMenu(activateFirst = false) {\n // If the item is not a valid submenu, close the child menu.\n let item = this.activeItem;\n if (!item || item.type !== 'submenu' || !item.submenu) {\n this._closeChildMenu();\n return;\n }\n // Do nothing if the child menu will not change.\n let submenu = item.submenu;\n if (submenu === this._childMenu) {\n return;\n }\n // Prior to any DOM modifications save window data\n Menu.saveWindowData();\n // Ensure the current child menu is closed.\n this._closeChildMenu();\n // Update the private child state.\n this._childMenu = submenu;\n this._childIndex = this._activeIndex;\n // Set the parent menu reference for the child.\n submenu._parentMenu = this;\n // Ensure the menu is updated and lookup the item node.\n MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);\n let itemNode = this.contentNode.children[this._activeIndex];\n // Open the submenu at the active node.\n Private$9.openSubmenu(submenu, itemNode);\n // Activate the first item if desired.\n if (activateFirst) {\n submenu.activeIndex = -1;\n submenu.activateNextItem();\n }\n // Activate the child menu.\n submenu.activate();\n }\n /**\n * Close the child menu immediately.\n *\n * This is a no-op if a child menu is not open.\n */\n _closeChildMenu() {\n if (this._childMenu) {\n this._childMenu.close();\n }\n }\n /**\n * Start the open timer, unless it is already pending.\n */\n _startOpenTimer() {\n if (this._openTimerID === 0) {\n this._openTimerID = window.setTimeout(() => {\n this._openTimerID = 0;\n this._openChildMenu();\n }, Private$9.TIMER_DELAY);\n }\n }\n /**\n * Start the close timer, unless it is already pending.\n */\n _startCloseTimer() {\n if (this._closeTimerID === 0) {\n this._closeTimerID = window.setTimeout(() => {\n this._closeTimerID = 0;\n this._closeChildMenu();\n }, Private$9.TIMER_DELAY);\n }\n }\n /**\n * Cancel the open timer, if the timer is pending.\n */\n _cancelOpenTimer() {\n if (this._openTimerID !== 0) {\n clearTimeout(this._openTimerID);\n this._openTimerID = 0;\n }\n }\n /**\n * Cancel the close timer, if the timer is pending.\n */\n _cancelCloseTimer() {\n if (this._closeTimerID !== 0) {\n clearTimeout(this._closeTimerID);\n this._closeTimerID = 0;\n }\n }\n /**\n * Save window data used for menu positioning in transient cache.\n *\n * In order to avoid layout trashing it is recommended to invoke this\n * method immediately prior to opening the menu and any DOM modifications\n * (like closing previously visible menu, or adding a class to menu widget).\n *\n * The transient cache will be released upon `open()` call.\n */\n static saveWindowData() {\n Private$9.saveWindowData();\n }\n}\n/**\n * The namespace for the `Menu` class statics.\n */\n(function (Menu) {\n /**\n * The default implementation of `IRenderer`.\n *\n * #### Notes\n * Subclasses are free to reimplement rendering methods as needed.\n */\n class Renderer {\n /**\n * Render the virtual element for a menu item.\n *\n * @param data - The data to use for rendering the item.\n *\n * @returns A virtual element representing the item.\n */\n renderItem(data) {\n let className = this.createItemClass(data);\n let dataset = this.createItemDataset(data);\n let aria = this.createItemARIA(data);\n return h.li({\n className,\n dataset,\n tabindex: '0',\n onfocus: data.onfocus,\n ...aria\n }, this.renderIcon(data), this.renderLabel(data), this.renderShortcut(data), this.renderSubmenu(data));\n }\n /**\n * Render the icon element for a menu item.\n *\n * @param data - The data to use for rendering the icon.\n *\n * @returns A virtual element representing the item icon.\n */\n renderIcon(data) {\n let className = this.createIconClass(data);\n // If data.item.icon is undefined, it will be ignored.\n return h.div({ className }, data.item.icon, data.item.iconLabel);\n }\n /**\n * Render the label element for a menu item.\n *\n * @param data - The data to use for rendering the label.\n *\n * @returns A virtual element representing the item label.\n */\n renderLabel(data) {\n let content = this.formatLabel(data);\n return h.div({ className: 'lm-Menu-itemLabel' }, content);\n }\n /**\n * Render the shortcut element for a menu item.\n *\n * @param data - The data to use for rendering the shortcut.\n *\n * @returns A virtual element representing the item shortcut.\n */\n renderShortcut(data) {\n let content = this.formatShortcut(data);\n return h.div({ className: 'lm-Menu-itemShortcut' }, content);\n }\n /**\n * Render the submenu icon element for a menu item.\n *\n * @param data - The data to use for rendering the submenu icon.\n *\n * @returns A virtual element representing the submenu icon.\n */\n renderSubmenu(data) {\n return h.div({ className: 'lm-Menu-itemSubmenuIcon' });\n }\n /**\n * Create the class name for the menu item.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the menu item.\n */\n createItemClass(data) {\n // Setup the initial class name.\n let name = 'lm-Menu-item';\n // Add the boolean state classes.\n if (!data.item.isEnabled) {\n name += ' lm-mod-disabled';\n }\n if (data.item.isToggled) {\n name += ' lm-mod-toggled';\n }\n if (!data.item.isVisible) {\n name += ' lm-mod-hidden';\n }\n if (data.active) {\n name += ' lm-mod-active';\n }\n if (data.collapsed) {\n name += ' lm-mod-collapsed';\n }\n // Add the extra class.\n let extra = data.item.className;\n if (extra) {\n name += ` ${extra}`;\n }\n // Return the complete class name.\n return name;\n }\n /**\n * Create the dataset for the menu item.\n *\n * @param data - The data to use for creating the dataset.\n *\n * @returns The dataset for the menu item.\n */\n createItemDataset(data) {\n let result;\n let { type, command, dataset } = data.item;\n if (type === 'command') {\n result = { ...dataset, type, command };\n }\n else {\n result = { ...dataset, type };\n }\n return result;\n }\n /**\n * Create the class name for the menu item icon.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the item icon.\n */\n createIconClass(data) {\n let name = 'lm-Menu-itemIcon';\n let extra = data.item.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n /**\n * Create the aria attributes for menu item.\n *\n * @param data - The data to use for the aria attributes.\n *\n * @returns The aria attributes object for the item.\n */\n createItemARIA(data) {\n let aria = {};\n switch (data.item.type) {\n case 'separator':\n aria.role = 'presentation';\n break;\n case 'submenu':\n aria['aria-haspopup'] = 'true';\n if (!data.item.isEnabled) {\n aria['aria-disabled'] = 'true';\n }\n break;\n default:\n if (!data.item.isEnabled) {\n aria['aria-disabled'] = 'true';\n }\n aria.role = 'menuitem';\n }\n return aria;\n }\n /**\n * Create the render content for the label node.\n *\n * @param data - The data to use for the label content.\n *\n * @returns The content to add to the label node.\n */\n formatLabel(data) {\n // Fetch the label text and mnemonic index.\n let { label, mnemonic } = data.item;\n // If the index is out of range, do not modify the label.\n if (mnemonic < 0 || mnemonic >= label.length) {\n return label;\n }\n // Split the label into parts.\n let prefix = label.slice(0, mnemonic);\n let suffix = label.slice(mnemonic + 1);\n let char = label[mnemonic];\n // Wrap the mnemonic character in a span.\n let span = h.span({ className: 'lm-Menu-itemMnemonic' }, char);\n // Return the content parts.\n return [prefix, span, suffix];\n }\n /**\n * Create the render content for the shortcut node.\n *\n * @param data - The data to use for the shortcut content.\n *\n * @returns The content to add to the shortcut node.\n */\n formatShortcut(data) {\n let kb = data.item.keyBinding;\n return kb ? CommandRegistry.formatKeystroke(kb.keys) : null;\n }\n }\n Menu.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n Menu.defaultRenderer = new Renderer();\n})(Menu || (Menu = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$9;\n(function (Private) {\n /**\n * The ms delay for opening and closing a submenu.\n */\n Private.TIMER_DELAY = 300;\n /**\n * The horizontal pixel overlap for an open submenu.\n */\n Private.SUBMENU_OVERLAP = 3;\n let transientWindowDataCache = null;\n let transientCacheCounter = 0;\n function getWindowData() {\n // if transient cache is in use, take one from it\n if (transientCacheCounter > 0) {\n transientCacheCounter--;\n return transientWindowDataCache;\n }\n return _getWindowData();\n }\n /**\n * Store window data in transient cache.\n *\n * The transient cache will be released upon `getWindowData()` call.\n * If this function is called multiple times, the cache will be\n * retained until as many calls to `getWindowData()` were made.\n *\n * Note: should be called before any DOM modifications.\n */\n function saveWindowData() {\n transientWindowDataCache = _getWindowData();\n transientCacheCounter++;\n }\n Private.saveWindowData = saveWindowData;\n /**\n * Create the DOM node for a menu.\n */\n function createNode() {\n let node = document.createElement('div');\n let content = document.createElement('ul');\n content.className = 'lm-Menu-content';\n node.appendChild(content);\n content.setAttribute('role', 'menu');\n node.tabIndex = 0;\n return node;\n }\n Private.createNode = createNode;\n /**\n * Test whether a menu item can be activated.\n */\n function canActivate(item) {\n return item.type !== 'separator' && item.isEnabled && item.isVisible;\n }\n Private.canActivate = canActivate;\n /**\n * Create a new menu item for an owner menu.\n */\n function createItem(owner, options) {\n return new MenuItem(owner.commands, options);\n }\n Private.createItem = createItem;\n /**\n * Hit test a menu hierarchy starting at the given root.\n */\n function hitTestMenus(menu, x, y) {\n for (let temp = menu; temp; temp = temp.childMenu) {\n if (ElementExt.hitTest(temp.node, x, y)) {\n return true;\n }\n }\n return false;\n }\n Private.hitTestMenus = hitTestMenus;\n /**\n * Compute which extra separator items should be collapsed.\n */\n function computeCollapsed(items) {\n // Allocate the return array and fill it with `false`.\n let result = new Array(items.length);\n ArrayExt.fill(result, false);\n // Collapse the leading separators.\n let k1 = 0;\n let n = items.length;\n for (; k1 < n; ++k1) {\n let item = items[k1];\n if (!item.isVisible) {\n continue;\n }\n if (item.type !== 'separator') {\n break;\n }\n result[k1] = true;\n }\n // Hide the trailing separators.\n let k2 = n - 1;\n for (; k2 >= 0; --k2) {\n let item = items[k2];\n if (!item.isVisible) {\n continue;\n }\n if (item.type !== 'separator') {\n break;\n }\n result[k2] = true;\n }\n // Hide the remaining consecutive separators.\n let hide = false;\n while (++k1 < k2) {\n let item = items[k1];\n if (!item.isVisible) {\n continue;\n }\n if (item.type !== 'separator') {\n hide = false;\n }\n else if (hide) {\n result[k1] = true;\n }\n else {\n hide = true;\n }\n }\n // Return the resulting flags.\n return result;\n }\n Private.computeCollapsed = computeCollapsed;\n function _getWindowData() {\n return {\n pageXOffset: window.pageXOffset,\n pageYOffset: window.pageYOffset,\n clientWidth: document.documentElement.clientWidth,\n clientHeight: document.documentElement.clientHeight\n };\n }\n /**\n * Open a menu as a root menu at the target location.\n */\n function openRootMenu(menu, x, y, forceX, forceY) {\n // Get the current position and size of the main viewport.\n const windowData = getWindowData();\n let px = windowData.pageXOffset;\n let py = windowData.pageYOffset;\n let cw = windowData.clientWidth;\n let ch = windowData.clientHeight;\n // Ensure the menu is updated before attaching and measuring.\n MessageLoop.sendMessage(menu, Widget.Msg.UpdateRequest);\n // Compute the maximum allowed height for the menu.\n let maxHeight = ch - (forceY ? y : 0);\n // Fetch common variables.\n let node = menu.node;\n let style = node.style;\n // Clear the menu geometry and prepare it for measuring.\n style.opacity = '0';\n style.maxHeight = `${maxHeight}px`;\n // Attach the menu to the document.\n Widget.attach(menu, document.body);\n // Measure the size of the menu.\n let { width, height } = node.getBoundingClientRect();\n // Adjust the X position of the menu to fit on-screen.\n if (!forceX && x + width > px + cw) {\n x = px + cw - width;\n }\n // Adjust the Y position of the menu to fit on-screen.\n if (!forceY && y + height > py + ch) {\n if (y > py + ch) {\n y = py + ch - height;\n }\n else {\n y = y - height;\n }\n }\n // Update the position of the menu to the computed position.\n style.transform = `translate(${Math.max(0, x)}px, ${Math.max(0, y)}px`;\n // Finally, make the menu visible on the screen.\n style.opacity = '1';\n }\n Private.openRootMenu = openRootMenu;\n /**\n * Open a menu as a submenu using an item node for positioning.\n */\n function openSubmenu(submenu, itemNode) {\n // Get the current position and size of the main viewport.\n const windowData = getWindowData();\n let px = windowData.pageXOffset;\n let py = windowData.pageYOffset;\n let cw = windowData.clientWidth;\n let ch = windowData.clientHeight;\n // Ensure the menu is updated before opening.\n MessageLoop.sendMessage(submenu, Widget.Msg.UpdateRequest);\n // Compute the maximum allowed height for the menu.\n let maxHeight = ch;\n // Fetch common variables.\n let node = submenu.node;\n let style = node.style;\n // Clear the menu geometry and prepare it for measuring.\n style.opacity = '0';\n style.maxHeight = `${maxHeight}px`;\n // Attach the menu to the document.\n Widget.attach(submenu, document.body);\n // Measure the size of the menu.\n let { width, height } = node.getBoundingClientRect();\n // Compute the box sizing for the menu.\n let box = ElementExt.boxSizing(submenu.node);\n // Get the bounding rect for the target item node.\n let itemRect = itemNode.getBoundingClientRect();\n // Compute the target X position.\n let x = itemRect.right - Private.SUBMENU_OVERLAP;\n // Adjust the X position to fit on the screen.\n if (x + width > px + cw) {\n x = itemRect.left + Private.SUBMENU_OVERLAP - width;\n }\n // Compute the target Y position.\n let y = itemRect.top - box.borderTop - box.paddingTop;\n // Adjust the Y position to fit on the screen.\n if (y + height > py + ch) {\n y = itemRect.bottom + box.borderBottom + box.paddingBottom - height;\n }\n // Update the position of the menu to the computed position.\n style.transform = `translate(${Math.max(0, x)}px, ${Math.max(0, y)}px`;\n // Finally, make the menu visible on the screen.\n style.opacity = '1';\n }\n Private.openSubmenu = openSubmenu;\n /**\n * Find the best matching mnemonic item.\n *\n * The search starts at the given index and wraps around.\n */\n function findMnemonic(items, key, start) {\n // Setup the result variables.\n let index = -1;\n let auto = -1;\n let multiple = false;\n // Normalize the key to upper case.\n let upperKey = key.toUpperCase();\n // Search the items from the given start index.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Compute the wrapped index.\n let k = (i + start) % n;\n // Lookup the item\n let item = items[k];\n // Ignore items which cannot be activated.\n if (!canActivate(item)) {\n continue;\n }\n // Ignore items with an empty label.\n let label = item.label;\n if (label.length === 0) {\n continue;\n }\n // Lookup the mnemonic index for the label.\n let mn = item.mnemonic;\n // Handle a valid mnemonic index.\n if (mn >= 0 && mn < label.length) {\n if (label[mn].toUpperCase() === upperKey) {\n if (index === -1) {\n index = k;\n }\n else {\n multiple = true;\n }\n }\n continue;\n }\n // Finally, handle the auto index if possible.\n if (auto === -1 && label[0].toUpperCase() === upperKey) {\n auto = k;\n }\n }\n // Return the search results.\n return { index, multiple, auto };\n }\n Private.findMnemonic = findMnemonic;\n /**\n * A concrete implementation of `Menu.IItem`.\n */\n class MenuItem {\n /**\n * Construct a new menu item.\n */\n constructor(commands, options) {\n this._commands = commands;\n this.type = options.type || 'command';\n this.command = options.command || '';\n this.args = options.args || JSONExt.emptyObject;\n this.submenu = options.submenu || null;\n }\n /**\n * The display label for the menu item.\n */\n get label() {\n if (this.type === 'command') {\n return this._commands.label(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.label;\n }\n return '';\n }\n /**\n * The mnemonic index for the menu item.\n */\n get mnemonic() {\n if (this.type === 'command') {\n return this._commands.mnemonic(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.mnemonic;\n }\n return -1;\n }\n /**\n * The icon renderer for the menu item.\n */\n get icon() {\n if (this.type === 'command') {\n return this._commands.icon(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.icon;\n }\n return undefined;\n }\n /**\n * The icon class for the menu item.\n */\n get iconClass() {\n if (this.type === 'command') {\n return this._commands.iconClass(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.iconClass;\n }\n return '';\n }\n /**\n * The icon label for the menu item.\n */\n get iconLabel() {\n if (this.type === 'command') {\n return this._commands.iconLabel(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.iconLabel;\n }\n return '';\n }\n /**\n * The display caption for the menu item.\n */\n get caption() {\n if (this.type === 'command') {\n return this._commands.caption(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.caption;\n }\n return '';\n }\n /**\n * The extra class name for the menu item.\n */\n get className() {\n if (this.type === 'command') {\n return this._commands.className(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.className;\n }\n return '';\n }\n /**\n * The dataset for the menu item.\n */\n get dataset() {\n if (this.type === 'command') {\n return this._commands.dataset(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.dataset;\n }\n return {};\n }\n /**\n * Whether the menu item is enabled.\n */\n get isEnabled() {\n if (this.type === 'command') {\n return this._commands.isEnabled(this.command, this.args);\n }\n if (this.type === 'submenu') {\n return this.submenu !== null;\n }\n return true;\n }\n /**\n * Whether the menu item is toggled.\n */\n get isToggled() {\n if (this.type === 'command') {\n return this._commands.isToggled(this.command, this.args);\n }\n return false;\n }\n /**\n * Whether the menu item is visible.\n */\n get isVisible() {\n if (this.type === 'command') {\n return this._commands.isVisible(this.command, this.args);\n }\n if (this.type === 'submenu') {\n return this.submenu !== null;\n }\n return true;\n }\n /**\n * The key binding for the menu item.\n */\n get keyBinding() {\n if (this.type === 'command') {\n let { command, args } = this;\n return (ArrayExt.findLastValue(this._commands.keyBindings, kb => {\n return kb.command === command && JSONExt.deepEqual(kb.args, args);\n }) || null);\n }\n return null;\n }\n }\n})(Private$9 || (Private$9 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * An object which implements a universal context menu.\n *\n * #### Notes\n * The items shown in the context menu are determined by CSS selector\n * matching against the DOM hierarchy at the site of the mouse click.\n * This is similar in concept to how keyboard shortcuts are matched\n * in the command registry.\n */\nclass ContextMenu {\n /**\n * Construct a new context menu.\n *\n * @param options - The options for initializing the menu.\n */\n constructor(options) {\n this._groupByTarget = true;\n this._idTick = 0;\n this._items = [];\n this._sortBySelector = true;\n const { groupByTarget, sortBySelector, ...others } = options;\n this.menu = new Menu(others);\n this._groupByTarget = groupByTarget !== false;\n this._sortBySelector = sortBySelector !== false;\n }\n /**\n * Add an item to the context menu.\n *\n * @param options - The options for creating the item.\n *\n * @returns A disposable which will remove the item from the menu.\n */\n addItem(options) {\n // Create an item from the given options.\n let item = Private$8.createItem(options, this._idTick++);\n // Add the item to the internal array.\n this._items.push(item);\n // Return a disposable which will remove the item.\n return new DisposableDelegate(() => {\n ArrayExt.removeFirstOf(this._items, item);\n });\n }\n /**\n * Open the context menu in response to a `'contextmenu'` event.\n *\n * @param event - The `'contextmenu'` event of interest.\n *\n * @returns `true` if the menu was opened, or `false` if no items\n * matched the event and the menu was not opened.\n *\n * #### Notes\n * This method will populate the context menu with items which match\n * the propagation path of the event, then open the menu at the mouse\n * position indicated by the event.\n */\n open(event) {\n // Prior to any DOM modifications update the window data.\n Menu.saveWindowData();\n // Clear the current contents of the context menu.\n this.menu.clearItems();\n // Bail early if there are no items to match.\n if (this._items.length === 0) {\n return false;\n }\n // Find the matching items for the event.\n let items = Private$8.matchItems(this._items, event, this._groupByTarget, this._sortBySelector);\n // Bail if there are no matching items.\n if (!items || items.length === 0) {\n return false;\n }\n // Add the filtered items to the menu.\n for (const item of items) {\n this.menu.addItem(item);\n }\n // Open the context menu at the current mouse position.\n this.menu.open(event.clientX, event.clientY);\n // Indicate success.\n return true;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$8;\n(function (Private) {\n /**\n * Create a normalized context menu item from an options object.\n */\n function createItem(options, id) {\n let selector = validateSelector(options.selector);\n let rank = options.rank !== undefined ? options.rank : Infinity;\n return { ...options, selector, rank, id };\n }\n Private.createItem = createItem;\n /**\n * Find the items which match a context menu event.\n *\n * The results are sorted by DOM level, specificity, and rank.\n */\n function matchItems(items, event, groupByTarget, sortBySelector) {\n // Look up the target of the event.\n let target = event.target;\n // Bail if there is no target.\n if (!target) {\n return null;\n }\n // Look up the current target of the event.\n let currentTarget = event.currentTarget;\n // Bail if there is no current target.\n if (!currentTarget) {\n return null;\n }\n // There are some third party libraries that cause the `target` to\n // be detached from the DOM before lumino can process the event.\n // If that happens, search for a new target node by point. If that\n // node is still dangling, bail.\n if (!currentTarget.contains(target)) {\n target = document.elementFromPoint(event.clientX, event.clientY);\n if (!target || !currentTarget.contains(target)) {\n return null;\n }\n }\n // Set up the result array.\n let result = [];\n // Copy the items array to allow in-place modification.\n let availableItems = items.slice();\n // Walk up the DOM hierarchy searching for matches.\n while (target !== null) {\n // Set up the match array for this DOM level.\n let matches = [];\n // Search the remaining items for matches.\n for (let i = 0, n = availableItems.length; i < n; ++i) {\n // Fetch the item.\n let item = availableItems[i];\n // Skip items which are already consumed.\n if (!item) {\n continue;\n }\n // Skip items which do not match the element.\n if (!Selector.matches(target, item.selector)) {\n continue;\n }\n // Add the matched item to the result for this DOM level.\n matches.push(item);\n // Mark the item as consumed.\n availableItems[i] = null;\n }\n // Sort the matches for this level and add them to the results.\n if (matches.length !== 0) {\n if (groupByTarget) {\n matches.sort(sortBySelector ? itemCmp : itemCmpRank);\n }\n result.push(...matches);\n }\n // Stop searching at the limits of the DOM range.\n if (target === currentTarget) {\n break;\n }\n // Step to the parent DOM level.\n target = target.parentElement;\n }\n if (!groupByTarget) {\n result.sort(sortBySelector ? itemCmp : itemCmpRank);\n }\n // Return the matched and sorted results.\n return result;\n }\n Private.matchItems = matchItems;\n /**\n * Validate the selector for a menu item.\n *\n * This returns the validated selector, or throws if the selector is\n * invalid or contains commas.\n */\n function validateSelector(selector) {\n if (selector.indexOf(',') !== -1) {\n throw new Error(`Selector cannot contain commas: ${selector}`);\n }\n if (!Selector.isValid(selector)) {\n throw new Error(`Invalid selector: ${selector}`);\n }\n return selector;\n }\n /**\n * A sort comparison function for a context menu item by ranks.\n */\n function itemCmpRank(a, b) {\n // Sort based on rank.\n let r1 = a.rank;\n let r2 = b.rank;\n if (r1 !== r2) {\n return r1 < r2 ? -1 : 1; // Infinity-safe\n }\n // When all else fails, sort by item id.\n return a.id - b.id;\n }\n /**\n * A sort comparison function for a context menu item by selectors and ranks.\n */\n function itemCmp(a, b) {\n // Sort first based on selector specificity.\n let s1 = Selector.calculateSpecificity(a.selector);\n let s2 = Selector.calculateSpecificity(b.selector);\n if (s1 !== s2) {\n return s2 - s1;\n }\n // If specificities are equal\n return itemCmpRank(a, b);\n }\n})(Private$8 || (Private$8 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nconst ARROW_KEYS = [\n 'ArrowLeft',\n 'ArrowUp',\n 'ArrowRight',\n 'ArrowDown',\n 'Home',\n 'End'\n];\n/**\n * A widget which displays titles as a single row or column of tabs.\n *\n * #### Notes\n * If CSS transforms are used to rotate nodes for vertically oriented\n * text, then tab dragging will not work correctly. The `tabsMovable`\n * property should be set to `false` when rotating nodes from CSS.\n */\nclass TabBar extends Widget {\n /**\n * Construct a new tab bar.\n *\n * @param options - The options for initializing the tab bar.\n */\n constructor(options = {}) {\n super({ node: Private$7.createNode() });\n this._currentIndex = -1;\n this._titles = [];\n this._titlesEditable = false;\n this._previousTitle = null;\n this._dragData = null;\n this._addButtonEnabled = false;\n this._tabMoved = new Signal(this);\n this._currentChanged = new Signal(this);\n this._addRequested = new Signal(this);\n this._tabCloseRequested = new Signal(this);\n this._tabDetachRequested = new Signal(this);\n this._tabActivateRequested = new Signal(this);\n this.addClass('lm-TabBar');\n this.contentNode.setAttribute('role', 'tablist');\n this.setFlag(Widget.Flag.DisallowLayout);\n this._document = options.document || document;\n this.tabsMovable = options.tabsMovable || false;\n this.titlesEditable = options.titlesEditable || false;\n this.allowDeselect = options.allowDeselect || false;\n this.addButtonEnabled = options.addButtonEnabled || false;\n this.insertBehavior = options.insertBehavior || 'select-tab-if-needed';\n this.name = options.name || '';\n this.orientation = options.orientation || 'horizontal';\n this.removeBehavior = options.removeBehavior || 'select-tab-after';\n this.renderer = options.renderer || TabBar.defaultRenderer;\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n this._releaseMouse();\n this._titles.length = 0;\n this._previousTitle = null;\n super.dispose();\n }\n /**\n * A signal emitted when the current tab is changed.\n *\n * #### Notes\n * This signal is emitted when the currently selected tab is changed\n * either through user or programmatic interaction.\n *\n * Notably, this signal is not emitted when the index of the current\n * tab changes due to tabs being inserted, removed, or moved. It is\n * only emitted when the actual current tab node is changed.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * A signal emitted when a tab is moved by the user.\n *\n * #### Notes\n * This signal is emitted when a tab is moved by user interaction.\n *\n * This signal is not emitted when a tab is moved programmatically.\n */\n get tabMoved() {\n return this._tabMoved;\n }\n /**\n * A signal emitted when a tab is clicked by the user.\n *\n * #### Notes\n * If the clicked tab is not the current tab, the clicked tab will be\n * made current and the `currentChanged` signal will be emitted first.\n *\n * This signal is emitted even if the clicked tab is the current tab.\n */\n get tabActivateRequested() {\n return this._tabActivateRequested;\n }\n /**\n * A signal emitted when the tab bar add button is clicked.\n */\n get addRequested() {\n return this._addRequested;\n }\n /**\n * A signal emitted when a tab close icon is clicked.\n *\n * #### Notes\n * This signal is not emitted unless the tab title is `closable`.\n */\n get tabCloseRequested() {\n return this._tabCloseRequested;\n }\n /**\n * A signal emitted when a tab is dragged beyond the detach threshold.\n *\n * #### Notes\n * This signal is emitted when the user drags a tab with the mouse,\n * and mouse is dragged beyond the detach threshold.\n *\n * The consumer of the signal should call `releaseMouse` and remove\n * the tab in order to complete the detach.\n *\n * This signal is only emitted once per drag cycle.\n */\n get tabDetachRequested() {\n return this._tabDetachRequested;\n }\n /**\n * The document to use with the tab bar.\n *\n * The default is the global `document` instance.\n */\n get document() {\n return this._document;\n }\n /**\n * Whether the titles can be user-edited.\n *\n */\n get titlesEditable() {\n return this._titlesEditable;\n }\n /**\n * Set whether titles can be user edited.\n *\n */\n set titlesEditable(value) {\n this._titlesEditable = value;\n }\n /**\n * Get the currently selected title.\n *\n * #### Notes\n * This will be `null` if no tab is selected.\n */\n get currentTitle() {\n return this._titles[this._currentIndex] || null;\n }\n /**\n * Set the currently selected title.\n *\n * #### Notes\n * If the title does not exist, the title will be set to `null`.\n */\n set currentTitle(value) {\n this.currentIndex = value ? this._titles.indexOf(value) : -1;\n }\n /**\n * Get the index of the currently selected tab.\n *\n * #### Notes\n * This will be `-1` if no tab is selected.\n */\n get currentIndex() {\n return this._currentIndex;\n }\n /**\n * Set the index of the currently selected tab.\n *\n * #### Notes\n * If the value is out of range, the index will be set to `-1`.\n */\n set currentIndex(value) {\n // Adjust for an out of range index.\n if (value < 0 || value >= this._titles.length) {\n value = -1;\n }\n // Bail early if the index will not change.\n if (this._currentIndex === value) {\n return;\n }\n // Look up the previous index and title.\n let pi = this._currentIndex;\n let pt = this._titles[pi] || null;\n // Look up the current index and title.\n let ci = value;\n let ct = this._titles[ci] || null;\n // Update the current index and previous title.\n this._currentIndex = ci;\n this._previousTitle = pt;\n // Schedule an update of the tabs.\n this.update();\n // Emit the current changed signal.\n this._currentChanged.emit({\n previousIndex: pi,\n previousTitle: pt,\n currentIndex: ci,\n currentTitle: ct\n });\n }\n /**\n * Get the name of the tab bar.\n */\n get name() {\n return this._name;\n }\n /**\n * Set the name of the tab bar.\n */\n set name(value) {\n this._name = value;\n if (value) {\n this.contentNode.setAttribute('aria-label', value);\n }\n else {\n this.contentNode.removeAttribute('aria-label');\n }\n }\n /**\n * Get the orientation of the tab bar.\n *\n * #### Notes\n * This controls whether the tabs are arranged in a row or column.\n */\n get orientation() {\n return this._orientation;\n }\n /**\n * Set the orientation of the tab bar.\n *\n * #### Notes\n * This controls whether the tabs are arranged in a row or column.\n */\n set orientation(value) {\n // Do nothing if the orientation does not change.\n if (this._orientation === value) {\n return;\n }\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Toggle the orientation values.\n this._orientation = value;\n this.dataset['orientation'] = value;\n this.contentNode.setAttribute('aria-orientation', value);\n }\n /**\n * Whether the add button is enabled.\n */\n get addButtonEnabled() {\n return this._addButtonEnabled;\n }\n /**\n * Set whether the add button is enabled.\n */\n set addButtonEnabled(value) {\n // Do nothing if the value does not change.\n if (this._addButtonEnabled === value) {\n return;\n }\n this._addButtonEnabled = value;\n if (value) {\n this.addButtonNode.classList.remove('lm-mod-hidden');\n }\n else {\n this.addButtonNode.classList.add('lm-mod-hidden');\n }\n }\n /**\n * A read-only array of the titles in the tab bar.\n */\n get titles() {\n return this._titles;\n }\n /**\n * The tab bar content node.\n *\n * #### Notes\n * This is the node which holds the tab nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-TabBar-content')[0];\n }\n /**\n * The tab bar add button node.\n *\n * #### Notes\n * This is the node which holds the add button.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get addButtonNode() {\n return this.node.getElementsByClassName('lm-TabBar-addButton')[0];\n }\n /**\n * Add a tab to the end of the tab bar.\n *\n * @param value - The title which holds the data for the tab,\n * or an options object to convert to a title.\n *\n * @returns The title object added to the tab bar.\n *\n * #### Notes\n * If the title is already added to the tab bar, it will be moved.\n */\n addTab(value) {\n return this.insertTab(this._titles.length, value);\n }\n /**\n * Insert a tab into the tab bar at the specified index.\n *\n * @param index - The index at which to insert the tab.\n *\n * @param value - The title which holds the data for the tab,\n * or an options object to convert to a title.\n *\n * @returns The title object added to the tab bar.\n *\n * #### Notes\n * The index will be clamped to the bounds of the tabs.\n *\n * If the title is already added to the tab bar, it will be moved.\n */\n insertTab(index, value) {\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Coerce the value to a title.\n let title = Private$7.asTitle(value);\n // Look up the index of the title.\n let i = this._titles.indexOf(title);\n // Clamp the insert index to the array bounds.\n let j = Math.max(0, Math.min(index, this._titles.length));\n // If the title is not in the array, insert it.\n if (i === -1) {\n // Insert the title into the array.\n ArrayExt.insert(this._titles, j, title);\n // Connect to the title changed signal.\n title.changed.connect(this._onTitleChanged, this);\n // Schedule an update of the tabs.\n this.update();\n // Adjust the current index for the insert.\n this._adjustCurrentForInsert(j, title);\n // Return the title added to the tab bar.\n return title;\n }\n // Otherwise, the title exists in the array and should be moved.\n // Adjust the index if the location is at the end of the array.\n if (j === this._titles.length) {\n j--;\n }\n // Bail if there is no effective move.\n if (i === j) {\n return title;\n }\n // Move the title to the new location.\n ArrayExt.move(this._titles, i, j);\n // Schedule an update of the tabs.\n this.update();\n // Adjust the current index for the move.\n this._adjustCurrentForMove(i, j);\n // Return the title added to the tab bar.\n return title;\n }\n /**\n * Remove a tab from the tab bar.\n *\n * @param title - The title for the tab to remove.\n *\n * #### Notes\n * This is a no-op if the title is not in the tab bar.\n */\n removeTab(title) {\n this.removeTabAt(this._titles.indexOf(title));\n }\n /**\n * Remove the tab at a given index from the tab bar.\n *\n * @param index - The index of the tab to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeTabAt(index) {\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Remove the title from the array.\n let title = ArrayExt.removeAt(this._titles, index);\n // Bail if the index is out of range.\n if (!title) {\n return;\n }\n // Disconnect from the title changed signal.\n title.changed.disconnect(this._onTitleChanged, this);\n // Clear the previous title if it's being removed.\n if (title === this._previousTitle) {\n this._previousTitle = null;\n }\n // Schedule an update of the tabs.\n this.update();\n // Adjust the current index for the remove.\n this._adjustCurrentForRemove(index, title);\n }\n /**\n * Remove all tabs from the tab bar.\n */\n clearTabs() {\n // Bail if there is nothing to remove.\n if (this._titles.length === 0) {\n return;\n }\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Disconnect from the title changed signals.\n for (let title of this._titles) {\n title.changed.disconnect(this._onTitleChanged, this);\n }\n // Get the current index and title.\n let pi = this.currentIndex;\n let pt = this.currentTitle;\n // Reset the current index and previous title.\n this._currentIndex = -1;\n this._previousTitle = null;\n // Clear the title array.\n this._titles.length = 0;\n // Schedule an update of the tabs.\n this.update();\n // If no tab was selected, there's nothing else to do.\n if (pi === -1) {\n return;\n }\n // Emit the current changed signal.\n this._currentChanged.emit({\n previousIndex: pi,\n previousTitle: pt,\n currentIndex: -1,\n currentTitle: null\n });\n }\n /**\n * Release the mouse and restore the non-dragged tab positions.\n *\n * #### Notes\n * This will cause the tab bar to stop handling mouse events and to\n * restore the tabs to their non-dragged positions.\n */\n releaseMouse() {\n this._releaseMouse();\n }\n /**\n * Handle the DOM events for the tab bar.\n *\n * @param event - The DOM event sent to the tab bar.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the tab bar's DOM node.\n *\n * This should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'pointerdown':\n this._evtPointerDown(event);\n break;\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'dblclick':\n this._evtDblClick(event);\n break;\n case 'keydown':\n event.eventPhase === Event.CAPTURING_PHASE\n ? this._evtKeyDownCapturing(event)\n : this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('pointerdown', this);\n this.node.addEventListener('dblclick', this);\n this.node.addEventListener('keydown', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('pointerdown', this);\n this.node.removeEventListener('dblclick', this);\n this.node.removeEventListener('keydown', this);\n this._releaseMouse();\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n var _a;\n let titles = this._titles;\n let renderer = this.renderer;\n let currentTitle = this.currentTitle;\n let content = new Array(titles.length);\n // Keep the tabindex=\"0\" attribute to the tab which handled it before the update.\n // If the add button handles it, no need to do anything. If no element of the tab\n // bar handles it, set it on the current or the first tab to ensure one element\n // handles it after update.\n const tabHandlingTabindex = (_a = this._getCurrentTabindex()) !== null && _a !== void 0 ? _a : (this._currentIndex > -1 ? this._currentIndex : 0);\n for (let i = 0, n = titles.length; i < n; ++i) {\n let title = titles[i];\n let current = title === currentTitle;\n let zIndex = current ? n : n - i - 1;\n let tabIndex = tabHandlingTabindex === i ? 0 : -1;\n content[i] = renderer.renderTab({ title, current, zIndex, tabIndex });\n }\n VirtualDOM.render(content, this.contentNode);\n }\n /**\n * Get the index of the tab which handles tabindex=\"0\".\n * If the add button handles tabindex=\"0\", -1 is returned.\n * If none of the previous handles tabindex=\"0\", null is returned.\n */\n _getCurrentTabindex() {\n let index = null;\n const elemTabindex = this.contentNode.querySelector('li[tabindex=\"0\"]');\n if (elemTabindex) {\n index = [...this.contentNode.children].indexOf(elemTabindex);\n }\n else if (this._addButtonEnabled &&\n this.addButtonNode.getAttribute('tabindex') === '0') {\n index = -1;\n }\n return index;\n }\n /**\n * Handle the `'dblclick'` event for the tab bar.\n */\n _evtDblClick(event) {\n // Do nothing if titles are not editable\n if (!this.titlesEditable) {\n return;\n }\n let tabs = this.contentNode.children;\n // Find the index of the targeted tab.\n let index = ArrayExt.findFirstIndex(tabs, tab => {\n return ElementExt.hitTest(tab, event.clientX, event.clientY);\n });\n // Do nothing if the press is not on a tab.\n if (index === -1) {\n return;\n }\n let title = this.titles[index];\n let label = tabs[index].querySelector('.lm-TabBar-tabLabel');\n if (label && label.contains(event.target)) {\n let value = title.label || '';\n // Clear the label element\n let oldValue = label.innerHTML;\n label.innerHTML = '';\n let input = document.createElement('input');\n input.classList.add('lm-TabBar-tabInput');\n input.value = value;\n label.appendChild(input);\n let onblur = () => {\n input.removeEventListener('blur', onblur);\n label.innerHTML = oldValue;\n this.node.addEventListener('keydown', this);\n };\n input.addEventListener('dblclick', (event) => event.stopPropagation());\n input.addEventListener('blur', onblur);\n input.addEventListener('keydown', (event) => {\n if (event.key === 'Enter') {\n if (input.value !== '') {\n title.label = title.caption = input.value;\n }\n onblur();\n }\n else if (event.key === 'Escape') {\n onblur();\n }\n });\n this.node.removeEventListener('keydown', this);\n input.select();\n input.focus();\n if (label.children.length > 0) {\n label.children[0].focus();\n }\n }\n }\n /**\n * Handle the `'keydown'` event for the tab bar at capturing phase.\n */\n _evtKeyDownCapturing(event) {\n if (event.eventPhase !== Event.CAPTURING_PHASE) {\n return;\n }\n // Stop all input events during drag.\n event.preventDefault();\n event.stopPropagation();\n // Release the mouse if `Escape` is pressed.\n if (event.key === 'Escape') {\n this._releaseMouse();\n }\n }\n /**\n * Handle the `'keydown'` event for the tab bar at target phase.\n */\n _evtKeyDown(event) {\n var _a, _b, _c;\n // Allow for navigation using tab key\n if (event.key === 'Tab' || event.eventPhase === Event.CAPTURING_PHASE) {\n return;\n }\n // Check if Enter or Spacebar key has been pressed and open that tab\n if (event.key === 'Enter' ||\n event.key === 'Spacebar' ||\n event.key === ' ') {\n // Get focus element that is in focus by the tab key\n const focusedElement = document.activeElement;\n // Test first if the focus is on the add button node\n if (this.addButtonEnabled &&\n this.addButtonNode.contains(focusedElement)) {\n event.preventDefault();\n event.stopPropagation();\n this._addRequested.emit();\n }\n else {\n const index = ArrayExt.findFirstIndex(this.contentNode.children, tab => tab.contains(focusedElement));\n if (index >= 0) {\n event.preventDefault();\n event.stopPropagation();\n this.currentIndex = index;\n }\n }\n // Handle the arrow keys to switch tabs.\n }\n else if (ARROW_KEYS.includes(event.key)) {\n // Create a list of all focusable elements in the tab bar.\n const focusable = [...this.contentNode.children];\n if (this.addButtonEnabled) {\n focusable.push(this.addButtonNode);\n }\n // If the tab bar contains only one element, nothing to do.\n if (focusable.length <= 1) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n // Get the current focused element.\n let focusedIndex = focusable.indexOf(document.activeElement);\n if (focusedIndex === -1) {\n focusedIndex = this._currentIndex;\n }\n // Find the next element to focus on.\n let nextFocused;\n if ((event.key === 'ArrowRight' && this._orientation === 'horizontal') ||\n (event.key === 'ArrowDown' && this._orientation === 'vertical')) {\n nextFocused = (_a = focusable[focusedIndex + 1]) !== null && _a !== void 0 ? _a : focusable[0];\n }\n else if ((event.key === 'ArrowLeft' && this._orientation === 'horizontal') ||\n (event.key === 'ArrowUp' && this._orientation === 'vertical')) {\n nextFocused =\n (_b = focusable[focusedIndex - 1]) !== null && _b !== void 0 ? _b : focusable[focusable.length - 1];\n }\n else if (event.key === 'Home') {\n nextFocused = focusable[0];\n }\n else if (event.key === 'End') {\n nextFocused = focusable[focusable.length - 1];\n }\n // Change the focused element and the tabindex value.\n if (nextFocused) {\n (_c = focusable[focusedIndex]) === null || _c === void 0 ? void 0 : _c.setAttribute('tabindex', '-1');\n nextFocused === null || nextFocused === void 0 ? void 0 : nextFocused.setAttribute('tabindex', '0');\n nextFocused.focus();\n }\n }\n }\n /**\n * Handle the `'pointerdown'` event for the tab bar.\n */\n _evtPointerDown(event) {\n // Do nothing if it's not a left or middle mouse press.\n if (event.button !== 0 && event.button !== 1) {\n return;\n }\n // Do nothing if a drag is in progress.\n if (this._dragData) {\n return;\n }\n // Do nothing if a title editable input was clicked.\n if (event.target.classList.contains('lm-TabBar-tabInput')) {\n return;\n }\n // Check if the add button was clicked.\n let addButtonClicked = this.addButtonEnabled &&\n this.addButtonNode.contains(event.target);\n // Lookup the tab nodes.\n let tabs = this.contentNode.children;\n // Find the index of the pressed tab.\n let index = ArrayExt.findFirstIndex(tabs, tab => {\n return ElementExt.hitTest(tab, event.clientX, event.clientY);\n });\n // Do nothing if the press is not on a tab or the add button.\n if (index === -1 && !addButtonClicked) {\n return;\n }\n // Pressing on a tab stops the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Initialize the non-measured parts of the drag data.\n this._dragData = {\n tab: tabs[index],\n index: index,\n pressX: event.clientX,\n pressY: event.clientY,\n tabPos: -1,\n tabSize: -1,\n tabPressPos: -1,\n targetIndex: -1,\n tabLayout: null,\n contentRect: null,\n override: null,\n dragActive: false,\n dragAborted: false,\n detachRequested: false\n };\n // Add the document pointer up listener.\n this.document.addEventListener('pointerup', this, true);\n // Do nothing else if the middle button or add button is clicked.\n if (event.button === 1 || addButtonClicked) {\n return;\n }\n // Do nothing else if the close icon is clicked.\n let icon = tabs[index].querySelector(this.renderer.closeIconSelector);\n if (icon && icon.contains(event.target)) {\n return;\n }\n // Add the extra listeners if the tabs are movable.\n if (this.tabsMovable) {\n this.document.addEventListener('pointermove', this, true);\n this.document.addEventListener('keydown', this, true);\n this.document.addEventListener('contextmenu', this, true);\n }\n // Update the current index as appropriate.\n if (this.allowDeselect && this.currentIndex === index) {\n this.currentIndex = -1;\n }\n else {\n this.currentIndex = index;\n }\n // Do nothing else if there is no current tab.\n if (this.currentIndex === -1) {\n return;\n }\n // Emit the tab activate request signal.\n this._tabActivateRequested.emit({\n index: this.currentIndex,\n title: this.currentTitle\n });\n }\n /**\n * Handle the `'pointermove'` event for the tab bar.\n */\n _evtPointerMove(event) {\n // Do nothing if no drag is in progress.\n let data = this._dragData;\n if (!data) {\n return;\n }\n // Suppress the event during a drag.\n event.preventDefault();\n event.stopPropagation();\n // Lookup the tab nodes.\n let tabs = this.contentNode.children;\n // Bail early if the drag threshold has not been met.\n if (!data.dragActive && !Private$7.dragExceeded(data, event)) {\n return;\n }\n // Activate the drag if necessary.\n if (!data.dragActive) {\n // Fill in the rest of the drag data measurements.\n let tabRect = data.tab.getBoundingClientRect();\n if (this._orientation === 'horizontal') {\n data.tabPos = data.tab.offsetLeft;\n data.tabSize = tabRect.width;\n data.tabPressPos = data.pressX - tabRect.left;\n }\n else {\n data.tabPos = data.tab.offsetTop;\n data.tabSize = tabRect.height;\n data.tabPressPos = data.pressY - tabRect.top;\n }\n data.tabPressOffset = {\n x: data.pressX - tabRect.left,\n y: data.pressY - tabRect.top\n };\n data.tabLayout = Private$7.snapTabLayout(tabs, this._orientation);\n data.contentRect = this.contentNode.getBoundingClientRect();\n data.override = Drag.overrideCursor('default');\n // Add the dragging style classes.\n data.tab.classList.add('lm-mod-dragging');\n this.addClass('lm-mod-dragging');\n // Mark the drag as active.\n data.dragActive = true;\n }\n // Emit the detach requested signal if the threshold is exceeded.\n if (!data.detachRequested && Private$7.detachExceeded(data, event)) {\n // Only emit the signal once per drag cycle.\n data.detachRequested = true;\n // Setup the arguments for the signal.\n let index = data.index;\n let clientX = event.clientX;\n let clientY = event.clientY;\n let tab = tabs[index];\n let title = this._titles[index];\n // Emit the tab detach requested signal.\n this._tabDetachRequested.emit({\n index,\n title,\n tab,\n clientX,\n clientY,\n offset: data.tabPressOffset\n });\n // Bail if the signal handler aborted the drag.\n if (data.dragAborted) {\n return;\n }\n }\n // Update the positions of the tabs.\n Private$7.layoutTabs(tabs, data, event, this._orientation);\n }\n /**\n * Handle the `'pointerup'` event for the document.\n */\n _evtPointerUp(event) {\n // Do nothing if it's not a left or middle mouse release.\n if (event.button !== 0 && event.button !== 1) {\n return;\n }\n // Do nothing if no drag is in progress.\n const data = this._dragData;\n if (!data) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Remove the extra mouse event listeners.\n this.document.removeEventListener('pointermove', this, true);\n this.document.removeEventListener('pointerup', this, true);\n this.document.removeEventListener('keydown', this, true);\n this.document.removeEventListener('contextmenu', this, true);\n // Handle a release when the drag is not active.\n if (!data.dragActive) {\n // Clear the drag data.\n this._dragData = null;\n // Handle clicking the add button.\n let addButtonClicked = this.addButtonEnabled &&\n this.addButtonNode.contains(event.target);\n if (addButtonClicked) {\n this._addRequested.emit(undefined);\n return;\n }\n // Lookup the tab nodes.\n let tabs = this.contentNode.children;\n // Find the index of the released tab.\n let index = ArrayExt.findFirstIndex(tabs, tab => {\n return ElementExt.hitTest(tab, event.clientX, event.clientY);\n });\n // Do nothing if the release is not on the original pressed tab.\n if (index !== data.index) {\n return;\n }\n // Ignore the release if the title is not closable.\n let title = this._titles[index];\n if (!title.closable) {\n return;\n }\n // Emit the close requested signal if the middle button is released.\n if (event.button === 1) {\n this._tabCloseRequested.emit({ index, title });\n return;\n }\n // Emit the close requested signal if the close icon was released.\n let icon = tabs[index].querySelector(this.renderer.closeIconSelector);\n if (icon && icon.contains(event.target)) {\n this._tabCloseRequested.emit({ index, title });\n return;\n }\n // Otherwise, there is nothing left to do.\n return;\n }\n // Do nothing if the left button is not released.\n if (event.button !== 0) {\n return;\n }\n // Position the tab at its final resting position.\n Private$7.finalizeTabPosition(data, this._orientation);\n // Remove the dragging class from the tab so it can be transitioned.\n data.tab.classList.remove('lm-mod-dragging');\n // Parse the transition duration for releasing the tab.\n let duration = Private$7.parseTransitionDuration(data.tab);\n // Complete the release on a timer to allow the tab to transition.\n setTimeout(() => {\n // Do nothing if the drag has been aborted.\n if (data.dragAborted) {\n return;\n }\n // Clear the drag data reference.\n this._dragData = null;\n // Reset the positions of the tabs.\n Private$7.resetTabPositions(this.contentNode.children, this._orientation);\n // Clear the cursor grab.\n data.override.dispose();\n // Remove the remaining dragging style.\n this.removeClass('lm-mod-dragging');\n // If the tab was not moved, there is nothing else to do.\n let i = data.index;\n let j = data.targetIndex;\n if (j === -1 || i === j) {\n return;\n }\n // Move the title to the new locations.\n ArrayExt.move(this._titles, i, j);\n // Adjust the current index for the move.\n this._adjustCurrentForMove(i, j);\n // Emit the tab moved signal.\n this._tabMoved.emit({\n fromIndex: i,\n toIndex: j,\n title: this._titles[j]\n });\n // Update the tabs immediately to prevent flicker.\n MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);\n }, duration);\n }\n /**\n * Release the mouse and restore the non-dragged tab positions.\n */\n _releaseMouse() {\n // Do nothing if no drag is in progress.\n let data = this._dragData;\n if (!data) {\n return;\n }\n // Clear the drag data reference.\n this._dragData = null;\n // Remove the extra document event listeners.\n this.document.removeEventListener('pointermove', this, true);\n this.document.removeEventListener('pointerup', this, true);\n this.document.removeEventListener('keydown', this, true);\n this.document.removeEventListener('contextmenu', this, true);\n // Indicate the drag has been aborted. This allows the mouse\n // event handlers to return early when the drag is canceled.\n data.dragAborted = true;\n // If the drag is not active, there's nothing more to do.\n if (!data.dragActive) {\n return;\n }\n // Reset the tabs to their non-dragged positions.\n Private$7.resetTabPositions(this.contentNode.children, this._orientation);\n // Clear the cursor override.\n data.override.dispose();\n // Clear the dragging style classes.\n data.tab.classList.remove('lm-mod-dragging');\n this.removeClass('lm-mod-dragging');\n }\n /**\n * Adjust the current index for a tab insert operation.\n *\n * This method accounts for the tab bar's insertion behavior when\n * adjusting the current index and emitting the changed signal.\n */\n _adjustCurrentForInsert(i, title) {\n // Lookup commonly used variables.\n let ct = this.currentTitle;\n let ci = this._currentIndex;\n let bh = this.insertBehavior;\n // TODO: do we need to do an update to update the aria-selected attribute?\n // Handle the behavior where the new tab is always selected,\n // or the behavior where the new tab is selected if needed.\n if (bh === 'select-tab' || (bh === 'select-tab-if-needed' && ci === -1)) {\n this._currentIndex = i;\n this._previousTitle = ct;\n this._currentChanged.emit({\n previousIndex: ci,\n previousTitle: ct,\n currentIndex: i,\n currentTitle: title\n });\n return;\n }\n // Otherwise, silently adjust the current index if needed.\n if (ci >= i) {\n this._currentIndex++;\n }\n }\n /**\n * Adjust the current index for a tab move operation.\n *\n * This method will not cause the actual current tab to change.\n * It silently adjusts the index to account for the given move.\n */\n _adjustCurrentForMove(i, j) {\n if (this._currentIndex === i) {\n this._currentIndex = j;\n }\n else if (this._currentIndex < i && this._currentIndex >= j) {\n this._currentIndex++;\n }\n else if (this._currentIndex > i && this._currentIndex <= j) {\n this._currentIndex--;\n }\n }\n /**\n * Adjust the current index for a tab remove operation.\n *\n * This method accounts for the tab bar's remove behavior when\n * adjusting the current index and emitting the changed signal.\n */\n _adjustCurrentForRemove(i, title) {\n // Lookup commonly used variables.\n let ci = this._currentIndex;\n let bh = this.removeBehavior;\n // Silently adjust the index if the current tab is not removed.\n if (ci !== i) {\n if (ci > i) {\n this._currentIndex--;\n }\n return;\n }\n // TODO: do we need to do an update to adjust the aria-selected value?\n // No tab gets selected if the tab bar is empty.\n if (this._titles.length === 0) {\n this._currentIndex = -1;\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: -1,\n currentTitle: null\n });\n return;\n }\n // Handle behavior where the next sibling tab is selected.\n if (bh === 'select-tab-after') {\n this._currentIndex = Math.min(i, this._titles.length - 1);\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: this._currentIndex,\n currentTitle: this.currentTitle\n });\n return;\n }\n // Handle behavior where the previous sibling tab is selected.\n if (bh === 'select-tab-before') {\n this._currentIndex = Math.max(0, i - 1);\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: this._currentIndex,\n currentTitle: this.currentTitle\n });\n return;\n }\n // Handle behavior where the previous history tab is selected.\n if (bh === 'select-previous-tab') {\n if (this._previousTitle) {\n this._currentIndex = this._titles.indexOf(this._previousTitle);\n this._previousTitle = null;\n }\n else {\n this._currentIndex = Math.min(i, this._titles.length - 1);\n }\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: this._currentIndex,\n currentTitle: this.currentTitle\n });\n return;\n }\n // Otherwise, no tab gets selected.\n this._currentIndex = -1;\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: -1,\n currentTitle: null\n });\n }\n /**\n * Handle the `changed` signal of a title object.\n */\n _onTitleChanged(sender) {\n this.update();\n }\n}\n/**\n * The namespace for the `TabBar` class statics.\n */\n(function (TabBar) {\n /**\n * The default implementation of `IRenderer`.\n *\n * #### Notes\n * Subclasses are free to reimplement rendering methods as needed.\n */\n class Renderer {\n constructor() {\n /**\n * A selector which matches the close icon node in a tab.\n */\n this.closeIconSelector = '.lm-TabBar-tabCloseIcon';\n this._tabID = 0;\n this._tabKeys = new WeakMap();\n this._uuid = ++Renderer._nInstance;\n }\n /**\n * Render the virtual element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab.\n */\n renderTab(data) {\n let title = data.title.caption;\n let key = this.createTabKey(data);\n let id = key;\n let style = this.createTabStyle(data);\n let className = this.createTabClass(data);\n let dataset = this.createTabDataset(data);\n let aria = this.createTabARIA(data);\n if (data.title.closable) {\n return h.li({ id, key, className, title, style, dataset, ...aria }, this.renderIcon(data), this.renderLabel(data), this.renderCloseIcon(data));\n }\n else {\n return h.li({ id, key, className, title, style, dataset, ...aria }, this.renderIcon(data), this.renderLabel(data));\n }\n }\n /**\n * Render the icon element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab icon.\n */\n renderIcon(data) {\n const { title } = data;\n let className = this.createIconClass(data);\n // If title.icon is undefined, it will be ignored.\n return h.div({ className }, title.icon, title.iconLabel);\n }\n /**\n * Render the label element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab label.\n */\n renderLabel(data) {\n return h.div({ className: 'lm-TabBar-tabLabel' }, data.title.label);\n }\n /**\n * Render the close icon element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab close icon.\n */\n renderCloseIcon(data) {\n return h.div({ className: 'lm-TabBar-tabCloseIcon' });\n }\n /**\n * Create a unique render key for the tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The unique render key for the tab.\n *\n * #### Notes\n * This method caches the key against the tab title the first time\n * the key is generated. This enables efficient rendering of moved\n * tabs and avoids subtle hover style artifacts.\n */\n createTabKey(data) {\n let key = this._tabKeys.get(data.title);\n if (key === undefined) {\n key = `tab-key-${this._uuid}-${this._tabID++}`;\n this._tabKeys.set(data.title, key);\n }\n return key;\n }\n /**\n * Create the inline style object for a tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The inline style data for the tab.\n */\n createTabStyle(data) {\n return { zIndex: `${data.zIndex}` };\n }\n /**\n * Create the class name for the tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The full class name for the tab.\n */\n createTabClass(data) {\n let name = 'lm-TabBar-tab';\n if (data.title.className) {\n name += ` ${data.title.className}`;\n }\n if (data.title.closable) {\n name += ' lm-mod-closable';\n }\n if (data.current) {\n name += ' lm-mod-current';\n }\n return name;\n }\n /**\n * Create the dataset for a tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The dataset for the tab.\n */\n createTabDataset(data) {\n return data.title.dataset;\n }\n /**\n * Create the ARIA attributes for a tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The ARIA attributes for the tab.\n */\n createTabARIA(data) {\n var _a;\n return {\n role: 'tab',\n 'aria-selected': data.current.toString(),\n tabindex: `${(_a = data.tabIndex) !== null && _a !== void 0 ? _a : '-1'}`\n };\n }\n /**\n * Create the class name for the tab icon.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The full class name for the tab icon.\n */\n createIconClass(data) {\n let name = 'lm-TabBar-tabIcon';\n let extra = data.title.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n }\n Renderer._nInstance = 0;\n TabBar.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n TabBar.defaultRenderer = new Renderer();\n /**\n * A selector which matches the add button node in the tab bar.\n */\n TabBar.addButtonSelector = '.lm-TabBar-addButton';\n})(TabBar || (TabBar = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$7;\n(function (Private) {\n /**\n * The start drag distance threshold.\n */\n Private.DRAG_THRESHOLD = 5;\n /**\n * The detach distance threshold.\n */\n Private.DETACH_THRESHOLD = 20;\n /**\n * Create the DOM node for a tab bar.\n */\n function createNode() {\n let node = document.createElement('div');\n let content = document.createElement('ul');\n content.setAttribute('role', 'tablist');\n content.className = 'lm-TabBar-content';\n node.appendChild(content);\n let add = document.createElement('div');\n add.className = 'lm-TabBar-addButton lm-mod-hidden';\n add.setAttribute('tabindex', '-1');\n add.setAttribute('role', 'button');\n node.appendChild(add);\n return node;\n }\n Private.createNode = createNode;\n /**\n * Coerce a title or options into a real title.\n */\n function asTitle(value) {\n return value instanceof Title ? value : new Title(value);\n }\n Private.asTitle = asTitle;\n /**\n * Parse the transition duration for a tab node.\n */\n function parseTransitionDuration(tab) {\n let style = window.getComputedStyle(tab);\n return 1000 * (parseFloat(style.transitionDuration) || 0);\n }\n Private.parseTransitionDuration = parseTransitionDuration;\n /**\n * Get a snapshot of the current tab layout values.\n */\n function snapTabLayout(tabs, orientation) {\n let layout = new Array(tabs.length);\n for (let i = 0, n = tabs.length; i < n; ++i) {\n let node = tabs[i];\n let style = window.getComputedStyle(node);\n if (orientation === 'horizontal') {\n layout[i] = {\n pos: node.offsetLeft,\n size: node.offsetWidth,\n margin: parseFloat(style.marginLeft) || 0\n };\n }\n else {\n layout[i] = {\n pos: node.offsetTop,\n size: node.offsetHeight,\n margin: parseFloat(style.marginTop) || 0\n };\n }\n }\n return layout;\n }\n Private.snapTabLayout = snapTabLayout;\n /**\n * Test if the event exceeds the drag threshold.\n */\n function dragExceeded(data, event) {\n let dx = Math.abs(event.clientX - data.pressX);\n let dy = Math.abs(event.clientY - data.pressY);\n return dx >= Private.DRAG_THRESHOLD || dy >= Private.DRAG_THRESHOLD;\n }\n Private.dragExceeded = dragExceeded;\n /**\n * Test if the event exceeds the drag detach threshold.\n */\n function detachExceeded(data, event) {\n let rect = data.contentRect;\n return (event.clientX < rect.left - Private.DETACH_THRESHOLD ||\n event.clientX >= rect.right + Private.DETACH_THRESHOLD ||\n event.clientY < rect.top - Private.DETACH_THRESHOLD ||\n event.clientY >= rect.bottom + Private.DETACH_THRESHOLD);\n }\n Private.detachExceeded = detachExceeded;\n /**\n * Update the relative tab positions and computed target index.\n */\n function layoutTabs(tabs, data, event, orientation) {\n // Compute the orientation-sensitive values.\n let pressPos;\n let localPos;\n let clientPos;\n let clientSize;\n if (orientation === 'horizontal') {\n pressPos = data.pressX;\n localPos = event.clientX - data.contentRect.left;\n clientPos = event.clientX;\n clientSize = data.contentRect.width;\n }\n else {\n pressPos = data.pressY;\n localPos = event.clientY - data.contentRect.top;\n clientPos = event.clientY;\n clientSize = data.contentRect.height;\n }\n // Compute the target data.\n let targetIndex = data.index;\n let targetPos = localPos - data.tabPressPos;\n let targetEnd = targetPos + data.tabSize;\n // Update the relative tab positions.\n for (let i = 0, n = tabs.length; i < n; ++i) {\n let pxPos;\n let layout = data.tabLayout[i];\n let threshold = layout.pos + (layout.size >> 1);\n if (i < data.index && targetPos < threshold) {\n pxPos = `${data.tabSize + data.tabLayout[i + 1].margin}px`;\n targetIndex = Math.min(targetIndex, i);\n }\n else if (i > data.index && targetEnd > threshold) {\n pxPos = `${-data.tabSize - layout.margin}px`;\n targetIndex = Math.max(targetIndex, i);\n }\n else if (i === data.index) {\n let ideal = clientPos - pressPos;\n let limit = clientSize - (data.tabPos + data.tabSize);\n pxPos = `${Math.max(-data.tabPos, Math.min(ideal, limit))}px`;\n }\n else {\n pxPos = '';\n }\n if (orientation === 'horizontal') {\n tabs[i].style.left = pxPos;\n }\n else {\n tabs[i].style.top = pxPos;\n }\n }\n // Update the computed target index.\n data.targetIndex = targetIndex;\n }\n Private.layoutTabs = layoutTabs;\n /**\n * Position the drag tab at its final resting relative position.\n */\n function finalizeTabPosition(data, orientation) {\n // Compute the orientation-sensitive client size.\n let clientSize;\n if (orientation === 'horizontal') {\n clientSize = data.contentRect.width;\n }\n else {\n clientSize = data.contentRect.height;\n }\n // Compute the ideal final tab position.\n let ideal;\n if (data.targetIndex === data.index) {\n ideal = 0;\n }\n else if (data.targetIndex > data.index) {\n let tgt = data.tabLayout[data.targetIndex];\n ideal = tgt.pos + tgt.size - data.tabSize - data.tabPos;\n }\n else {\n let tgt = data.tabLayout[data.targetIndex];\n ideal = tgt.pos - data.tabPos;\n }\n // Compute the tab position limit.\n let limit = clientSize - (data.tabPos + data.tabSize);\n let final = Math.max(-data.tabPos, Math.min(ideal, limit));\n // Set the final orientation-sensitive position.\n if (orientation === 'horizontal') {\n data.tab.style.left = `${final}px`;\n }\n else {\n data.tab.style.top = `${final}px`;\n }\n }\n Private.finalizeTabPosition = finalizeTabPosition;\n /**\n * Reset the relative positions of the given tabs.\n */\n function resetTabPositions(tabs, orientation) {\n for (const tab of tabs) {\n if (orientation === 'horizontal') {\n tab.style.left = '';\n }\n else {\n tab.style.top = '';\n }\n }\n }\n Private.resetTabPositions = resetTabPositions;\n})(Private$7 || (Private$7 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which provides a flexible docking arrangement.\n *\n * #### Notes\n * The consumer of this layout is responsible for handling all signals\n * from the generated tab bars and managing the visibility of widgets\n * and tab bars as needed.\n */\nclass DockLayout extends Layout {\n /**\n * Construct a new dock layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options) {\n super();\n this._spacing = 4;\n this._dirty = false;\n this._root = null;\n this._box = null;\n this._items = new Map();\n this.renderer = options.renderer;\n if (options.spacing !== undefined) {\n this._spacing = Utils$1.clampDimension(options.spacing);\n }\n this._document = options.document || document;\n this._hiddenMode =\n options.hiddenMode !== undefined\n ? options.hiddenMode\n : Widget.HiddenMode.Display;\n }\n /**\n * Dispose of the resources held by the layout.\n *\n * #### Notes\n * This will clear and dispose all widgets in the layout.\n */\n dispose() {\n // Get an iterator over the widgets in the layout.\n let widgets = this[Symbol.iterator]();\n // Dispose of the layout items.\n this._items.forEach(item => {\n item.dispose();\n });\n // Clear the layout state before disposing the widgets.\n this._box = null;\n this._root = null;\n this._items.clear();\n // Dispose of the widgets contained in the old layout root.\n for (const widget of widgets) {\n widget.dispose();\n }\n // Dispose of the base class.\n super.dispose();\n }\n /**\n * The method for hiding child widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n get hiddenMode() {\n return this._hiddenMode;\n }\n set hiddenMode(v) {\n if (this._hiddenMode === v) {\n return;\n }\n this._hiddenMode = v;\n for (const bar of this.tabBars()) {\n if (bar.titles.length > 1) {\n for (const title of bar.titles) {\n title.owner.hiddenMode = this._hiddenMode;\n }\n }\n }\n }\n /**\n * Get the inter-element spacing for the dock layout.\n */\n get spacing() {\n return this._spacing;\n }\n /**\n * Set the inter-element spacing for the dock layout.\n */\n set spacing(value) {\n value = Utils$1.clampDimension(value);\n if (this._spacing === value) {\n return;\n }\n this._spacing = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * Whether the dock layout is empty.\n */\n get isEmpty() {\n return this._root === null;\n }\n /**\n * Create an iterator over all widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n *\n * #### Notes\n * This iterator includes the generated tab bars.\n */\n [Symbol.iterator]() {\n return this._root ? this._root.iterAllWidgets() : empty();\n }\n /**\n * Create an iterator over the user widgets in the layout.\n *\n * @returns A new iterator over the user widgets in the layout.\n *\n * #### Notes\n * This iterator does not include the generated tab bars.\n */\n widgets() {\n return this._root ? this._root.iterUserWidgets() : empty();\n }\n /**\n * Create an iterator over the selected widgets in the layout.\n *\n * @returns A new iterator over the selected user widgets.\n *\n * #### Notes\n * This iterator yields the widgets corresponding to the current tab\n * of each tab bar in the layout.\n */\n selectedWidgets() {\n return this._root ? this._root.iterSelectedWidgets() : empty();\n }\n /**\n * Create an iterator over the tab bars in the layout.\n *\n * @returns A new iterator over the tab bars in the layout.\n *\n * #### Notes\n * This iterator does not include the user widgets.\n */\n tabBars() {\n return this._root ? this._root.iterTabBars() : empty();\n }\n /**\n * Create an iterator over the handles in the layout.\n *\n * @returns A new iterator over the handles in the layout.\n */\n handles() {\n return this._root ? this._root.iterHandles() : empty();\n }\n /**\n * Move a handle to the given offset position.\n *\n * @param handle - The handle to move.\n *\n * @param offsetX - The desired offset X position of the handle.\n *\n * @param offsetY - The desired offset Y position of the handle.\n *\n * #### Notes\n * If the given handle is not contained in the layout, this is no-op.\n *\n * The handle will be moved as close as possible to the desired\n * position without violating any of the layout constraints.\n *\n * Only one of the coordinates is used depending on the orientation\n * of the handle. This method accepts both coordinates to make it\n * easy to invoke from a mouse move event without needing to know\n * the handle orientation.\n */\n moveHandle(handle, offsetX, offsetY) {\n // Bail early if there is no root or if the handle is hidden.\n let hidden = handle.classList.contains('lm-mod-hidden');\n if (!this._root || hidden) {\n return;\n }\n // Lookup the split node for the handle.\n let data = this._root.findSplitNode(handle);\n if (!data) {\n return;\n }\n // Compute the desired delta movement for the handle.\n let delta;\n if (data.node.orientation === 'horizontal') {\n delta = offsetX - handle.offsetLeft;\n }\n else {\n delta = offsetY - handle.offsetTop;\n }\n // Bail if there is no handle movement.\n if (delta === 0) {\n return;\n }\n // Prevent sibling resizing unless needed.\n data.node.holdSizes();\n // Adjust the sizers to reflect the handle movement.\n BoxEngine.adjust(data.node.sizers, data.index, delta);\n // Update the layout of the widgets.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Save the current configuration of the dock layout.\n *\n * @returns A new config object for the current layout state.\n *\n * #### Notes\n * The return value can be provided to the `restoreLayout` method\n * in order to restore the layout to its current configuration.\n */\n saveLayout() {\n // Bail early if there is no root.\n if (!this._root) {\n return { main: null };\n }\n // Hold the current sizes in the layout tree.\n this._root.holdAllSizes();\n // Return the layout config.\n return { main: this._root.createConfig() };\n }\n /**\n * Restore the layout to a previously saved configuration.\n *\n * @param config - The layout configuration to restore.\n *\n * #### Notes\n * Widgets which currently belong to the layout but which are not\n * contained in the config will be unparented.\n */\n restoreLayout(config) {\n // Create the widget set for validating the config.\n let widgetSet = new Set();\n // Normalize the main area config and collect the widgets.\n let mainConfig;\n if (config.main) {\n mainConfig = Private$6.normalizeAreaConfig(config.main, widgetSet);\n }\n else {\n mainConfig = null;\n }\n // Create iterators over the old content.\n let oldWidgets = this.widgets();\n let oldTabBars = this.tabBars();\n let oldHandles = this.handles();\n // Clear the root before removing the old content.\n this._root = null;\n // Unparent the old widgets which are not in the new config.\n for (const widget of oldWidgets) {\n if (!widgetSet.has(widget)) {\n widget.parent = null;\n }\n }\n // Dispose of the old tab bars.\n for (const tabBar of oldTabBars) {\n tabBar.dispose();\n }\n // Remove the old handles.\n for (const handle of oldHandles) {\n if (handle.parentNode) {\n handle.parentNode.removeChild(handle);\n }\n }\n // Reparent the new widgets to the current parent.\n for (const widget of widgetSet) {\n widget.parent = this.parent;\n }\n // Create the root node for the new config.\n if (mainConfig) {\n this._root = Private$6.realizeAreaConfig(mainConfig, {\n // Ignoring optional `document` argument as we must reuse `this._document`\n createTabBar: (document) => this._createTabBar(),\n createHandle: () => this._createHandle()\n }, this._document);\n }\n else {\n this._root = null;\n }\n // If there is no parent, there is nothing more to do.\n if (!this.parent) {\n return;\n }\n // Attach the new widgets to the parent.\n widgetSet.forEach(widget => {\n this.attachWidget(widget);\n });\n // Post a fit request to the parent.\n this.parent.fit();\n }\n /**\n * Add a widget to the dock layout.\n *\n * @param widget - The widget to add to the dock layout.\n *\n * @param options - The additional options for adding the widget.\n *\n * #### Notes\n * The widget will be moved if it is already contained in the layout.\n *\n * An error will be thrown if the reference widget is invalid.\n */\n addWidget(widget, options = {}) {\n // Parse the options.\n let ref = options.ref || null;\n let mode = options.mode || 'tab-after';\n // Find the tab node which holds the reference widget.\n let refNode = null;\n if (this._root && ref) {\n refNode = this._root.findTabNode(ref);\n }\n // Throw an error if the reference widget is invalid.\n if (ref && !refNode) {\n throw new Error('Reference widget is not in the layout.');\n }\n // Reparent the widget to the current layout parent.\n widget.parent = this.parent;\n // Insert the widget according to the insert mode.\n switch (mode) {\n case 'tab-after':\n this._insertTab(widget, ref, refNode, true);\n break;\n case 'tab-before':\n this._insertTab(widget, ref, refNode, false);\n break;\n case 'split-top':\n this._insertSplit(widget, ref, refNode, 'vertical', false);\n break;\n case 'split-left':\n this._insertSplit(widget, ref, refNode, 'horizontal', false);\n break;\n case 'split-right':\n this._insertSplit(widget, ref, refNode, 'horizontal', true);\n break;\n case 'split-bottom':\n this._insertSplit(widget, ref, refNode, 'vertical', true);\n break;\n case 'merge-top':\n this._insertSplit(widget, ref, refNode, 'vertical', false, true);\n break;\n case 'merge-left':\n this._insertSplit(widget, ref, refNode, 'horizontal', false, true);\n break;\n case 'merge-right':\n this._insertSplit(widget, ref, refNode, 'horizontal', true, true);\n break;\n case 'merge-bottom':\n this._insertSplit(widget, ref, refNode, 'vertical', true, true);\n break;\n }\n // Do nothing else if there is no parent widget.\n if (!this.parent) {\n return;\n }\n // Ensure the widget is attached to the parent widget.\n this.attachWidget(widget);\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Remove a widget from the layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n // Remove the widget from its current layout location.\n this._removeWidget(widget);\n // Do nothing else if there is no parent widget.\n if (!this.parent) {\n return;\n }\n // Detach the widget from the parent widget.\n this.detachWidget(widget);\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Find the tab area which contains the given client position.\n *\n * @param clientX - The client X position of interest.\n *\n * @param clientY - The client Y position of interest.\n *\n * @returns The geometry of the tab area at the given position, or\n * `null` if there is no tab area at the given position.\n */\n hitTestTabAreas(clientX, clientY) {\n // Bail early if hit testing cannot produce valid results.\n if (!this._root || !this.parent || !this.parent.isVisible) {\n return null;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Convert from client to local coordinates.\n let rect = this.parent.node.getBoundingClientRect();\n let x = clientX - rect.left - this._box.borderLeft;\n let y = clientY - rect.top - this._box.borderTop;\n // Find the tab layout node at the local position.\n let tabNode = this._root.hitTestTabNodes(x, y);\n // Bail if a tab layout node was not found.\n if (!tabNode) {\n return null;\n }\n // Extract the data from the tab node.\n let { tabBar, top, left, width, height } = tabNode;\n // Compute the right and bottom edges of the tab area.\n let borderWidth = this._box.borderLeft + this._box.borderRight;\n let borderHeight = this._box.borderTop + this._box.borderBottom;\n let right = rect.width - borderWidth - (left + width);\n let bottom = rect.height - borderHeight - (top + height);\n // Return the hit test results.\n return { tabBar, x, y, top, left, right, bottom, width, height };\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n // Perform superclass initialization.\n super.init();\n // Attach each widget to the parent.\n for (const widget of this) {\n this.attachWidget(widget);\n }\n // Attach each handle to the parent.\n for (const handle of this.handles()) {\n this.parent.node.appendChild(handle);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Attach the widget to the layout parent widget.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a no-op if the widget is already attached.\n */\n attachWidget(widget) {\n // Do nothing if the widget is already attached.\n if (this.parent.node === widget.node.parentNode) {\n return;\n }\n // Create the layout item for the widget.\n this._items.set(widget, new LayoutItem(widget));\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Detach the widget from the layout parent widget.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a no-op if the widget is not attached.\n */\n detachWidget(widget) {\n // Do nothing if the widget is not attached.\n if (this.parent.node !== widget.node.parentNode) {\n return;\n }\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Delete the layout item for the widget.\n let item = this._items.get(widget);\n if (item) {\n this._items.delete(widget);\n item.dispose();\n }\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Remove the specified widget from the layout structure.\n *\n * #### Notes\n * This is a no-op if the widget is not in the layout tree.\n *\n * This does not detach the widget from the parent node.\n */\n _removeWidget(widget) {\n // Bail early if there is no layout root.\n if (!this._root) {\n return;\n }\n // Find the tab node which contains the given widget.\n let tabNode = this._root.findTabNode(widget);\n // Bail early if the tab node is not found.\n if (!tabNode) {\n return;\n }\n Private$6.removeAria(widget);\n // If there are multiple tabs, just remove the widget's tab.\n if (tabNode.tabBar.titles.length > 1) {\n tabNode.tabBar.removeTab(widget.title);\n if (this._hiddenMode === Widget.HiddenMode.Scale &&\n tabNode.tabBar.titles.length == 1) {\n const existingWidget = tabNode.tabBar.titles[0].owner;\n existingWidget.hiddenMode = Widget.HiddenMode.Display;\n }\n return;\n }\n // Otherwise, the tab node needs to be removed...\n // Dispose the tab bar.\n tabNode.tabBar.dispose();\n // Handle the case where the tab node is the root.\n if (this._root === tabNode) {\n this._root = null;\n return;\n }\n // Otherwise, remove the tab node from its parent...\n // Prevent widget resizing unless needed.\n this._root.holdAllSizes();\n // Clear the parent reference on the tab node.\n let splitNode = tabNode.parent;\n tabNode.parent = null;\n // Remove the tab node from its parent split node.\n let i = ArrayExt.removeFirstOf(splitNode.children, tabNode);\n let handle = ArrayExt.removeAt(splitNode.handles, i);\n ArrayExt.removeAt(splitNode.sizers, i);\n // Remove the handle from its parent DOM node.\n if (handle.parentNode) {\n handle.parentNode.removeChild(handle);\n }\n // If there are multiple children, just update the handles.\n if (splitNode.children.length > 1) {\n splitNode.syncHandles();\n return;\n }\n // Otherwise, the split node also needs to be removed...\n // Clear the parent reference on the split node.\n let maybeParent = splitNode.parent;\n splitNode.parent = null;\n // Lookup the remaining child node and handle.\n let childNode = splitNode.children[0];\n let childHandle = splitNode.handles[0];\n // Clear the split node data.\n splitNode.children.length = 0;\n splitNode.handles.length = 0;\n splitNode.sizers.length = 0;\n // Remove the child handle from its parent node.\n if (childHandle.parentNode) {\n childHandle.parentNode.removeChild(childHandle);\n }\n // Handle the case where the split node is the root.\n if (this._root === splitNode) {\n childNode.parent = null;\n this._root = childNode;\n return;\n }\n // Otherwise, move the child node to the parent node...\n let parentNode = maybeParent;\n // Lookup the index of the split node.\n let j = parentNode.children.indexOf(splitNode);\n // Handle the case where the child node is a tab node.\n if (childNode instanceof Private$6.TabLayoutNode) {\n childNode.parent = parentNode;\n parentNode.children[j] = childNode;\n return;\n }\n // Remove the split data from the parent.\n let splitHandle = ArrayExt.removeAt(parentNode.handles, j);\n ArrayExt.removeAt(parentNode.children, j);\n ArrayExt.removeAt(parentNode.sizers, j);\n // Remove the handle from its parent node.\n if (splitHandle.parentNode) {\n splitHandle.parentNode.removeChild(splitHandle);\n }\n // The child node and the split parent node will have the same\n // orientation. Merge the grand-children with the parent node.\n for (let i = 0, n = childNode.children.length; i < n; ++i) {\n let gChild = childNode.children[i];\n let gHandle = childNode.handles[i];\n let gSizer = childNode.sizers[i];\n ArrayExt.insert(parentNode.children, j + i, gChild);\n ArrayExt.insert(parentNode.handles, j + i, gHandle);\n ArrayExt.insert(parentNode.sizers, j + i, gSizer);\n gChild.parent = parentNode;\n }\n // Clear the child node.\n childNode.children.length = 0;\n childNode.handles.length = 0;\n childNode.sizers.length = 0;\n childNode.parent = null;\n // Sync the handles on the parent node.\n parentNode.syncHandles();\n }\n /**\n * Create the tab layout node to hold the widget.\n */\n _createTabNode(widget) {\n let tabNode = new Private$6.TabLayoutNode(this._createTabBar());\n tabNode.tabBar.addTab(widget.title);\n Private$6.addAria(widget, tabNode.tabBar);\n return tabNode;\n }\n /**\n * Insert a widget next to an existing tab.\n *\n * #### Notes\n * This does not attach the widget to the parent widget.\n */\n _insertTab(widget, ref, refNode, after) {\n // Do nothing if the tab is inserted next to itself.\n if (widget === ref) {\n return;\n }\n // Create the root if it does not exist.\n if (!this._root) {\n let tabNode = new Private$6.TabLayoutNode(this._createTabBar());\n tabNode.tabBar.addTab(widget.title);\n this._root = tabNode;\n Private$6.addAria(widget, tabNode.tabBar);\n return;\n }\n // Use the first tab node as the ref node if needed.\n if (!refNode) {\n refNode = this._root.findFirstTabNode();\n }\n // If the widget is not contained in the ref node, ensure it is\n // removed from the layout and hidden before being added again.\n if (refNode.tabBar.titles.indexOf(widget.title) === -1) {\n this._removeWidget(widget);\n widget.hide();\n }\n // Lookup the target index for inserting the tab.\n let index;\n if (ref) {\n index = refNode.tabBar.titles.indexOf(ref.title);\n }\n else {\n index = refNode.tabBar.currentIndex;\n }\n // Using transform create an additional layer in the pixel pipeline\n // to limit the number of layer, it is set only if there is more than one widget.\n if (this._hiddenMode === Widget.HiddenMode.Scale) {\n if (refNode.tabBar.titles.length === 0) {\n // Singular tab should use display mode to limit number of layers.\n widget.hiddenMode = Widget.HiddenMode.Display;\n }\n else if (refNode.tabBar.titles.length == 1) {\n // If we are adding a second tab, switch the existing tab back to scale.\n const existingWidget = refNode.tabBar.titles[0].owner;\n existingWidget.hiddenMode = Widget.HiddenMode.Scale;\n }\n else {\n // For the third and subsequent tabs no special action is needed.\n widget.hiddenMode = Widget.HiddenMode.Scale;\n }\n }\n else {\n // For all other modes just propagate the current mode.\n widget.hiddenMode = this._hiddenMode;\n }\n // Insert the widget's tab relative to the target index.\n refNode.tabBar.insertTab(index + (after ? 1 : 0), widget.title);\n Private$6.addAria(widget, refNode.tabBar);\n }\n /**\n * Insert a widget as a new split area.\n *\n * #### Notes\n * This does not attach the widget to the parent widget.\n */\n _insertSplit(widget, ref, refNode, orientation, after, merge = false) {\n // Do nothing if there is no effective split.\n if (widget === ref && refNode && refNode.tabBar.titles.length === 1) {\n return;\n }\n // Ensure the widget is removed from the current layout.\n this._removeWidget(widget);\n // Set the root if it does not exist.\n if (!this._root) {\n this._root = this._createTabNode(widget);\n return;\n }\n // If the ref node parent is null, split the root.\n if (!refNode || !refNode.parent) {\n // Ensure the root is split with the correct orientation.\n let root = this._splitRoot(orientation);\n // Determine the insert index for the new tab node.\n let i = after ? root.children.length : 0;\n // Normalize the split node.\n root.normalizeSizes();\n // Create the sizer for new tab node.\n let sizer = Private$6.createSizer(refNode ? 1 : Private$6.GOLDEN_RATIO);\n // Insert the tab node sized to the golden ratio.\n let tabNode = this._createTabNode(widget);\n ArrayExt.insert(root.children, i, tabNode);\n ArrayExt.insert(root.sizers, i, sizer);\n ArrayExt.insert(root.handles, i, this._createHandle());\n tabNode.parent = root;\n // Re-normalize the split node to maintain the ratios.\n root.normalizeSizes();\n // Finally, synchronize the visibility of the handles.\n root.syncHandles();\n return;\n }\n // Lookup the split node for the ref widget.\n let splitNode = refNode.parent;\n // If the split node already had the correct orientation,\n // the widget can be inserted into the split node directly.\n if (splitNode.orientation === orientation) {\n // Find the index of the ref node.\n let i = splitNode.children.indexOf(refNode);\n // Conditionally reuse a tab layout found in the wanted position.\n if (merge) {\n let j = i + (after ? 1 : -1);\n let sibling = splitNode.children[j];\n if (sibling instanceof Private$6.TabLayoutNode) {\n this._insertTab(widget, null, sibling, true);\n ++sibling.tabBar.currentIndex;\n return;\n }\n }\n // Normalize the split node.\n splitNode.normalizeSizes();\n // Consume half the space for the insert location.\n let s = (splitNode.sizers[i].sizeHint /= 2);\n // Insert the tab node sized to the other half.\n let j = i + (after ? 1 : 0);\n let tabNode = this._createTabNode(widget);\n ArrayExt.insert(splitNode.children, j, tabNode);\n ArrayExt.insert(splitNode.sizers, j, Private$6.createSizer(s));\n ArrayExt.insert(splitNode.handles, j, this._createHandle());\n tabNode.parent = splitNode;\n // Finally, synchronize the visibility of the handles.\n splitNode.syncHandles();\n return;\n }\n // Remove the ref node from the split node.\n let i = ArrayExt.removeFirstOf(splitNode.children, refNode);\n // Create a new normalized split node for the children.\n let childNode = new Private$6.SplitLayoutNode(orientation);\n childNode.normalized = true;\n // Add the ref node sized to half the space.\n childNode.children.push(refNode);\n childNode.sizers.push(Private$6.createSizer(0.5));\n childNode.handles.push(this._createHandle());\n refNode.parent = childNode;\n // Add the tab node sized to the other half.\n let j = after ? 1 : 0;\n let tabNode = this._createTabNode(widget);\n ArrayExt.insert(childNode.children, j, tabNode);\n ArrayExt.insert(childNode.sizers, j, Private$6.createSizer(0.5));\n ArrayExt.insert(childNode.handles, j, this._createHandle());\n tabNode.parent = childNode;\n // Synchronize the visibility of the handles.\n childNode.syncHandles();\n // Finally, add the new child node to the original split node.\n ArrayExt.insert(splitNode.children, i, childNode);\n childNode.parent = splitNode;\n }\n /**\n * Ensure the root is a split node with the given orientation.\n */\n _splitRoot(orientation) {\n // Bail early if the root already meets the requirements.\n let oldRoot = this._root;\n if (oldRoot instanceof Private$6.SplitLayoutNode) {\n if (oldRoot.orientation === orientation) {\n return oldRoot;\n }\n }\n // Create a new root node with the specified orientation.\n let newRoot = (this._root = new Private$6.SplitLayoutNode(orientation));\n // Add the old root to the new root.\n if (oldRoot) {\n newRoot.children.push(oldRoot);\n newRoot.sizers.push(Private$6.createSizer(0));\n newRoot.handles.push(this._createHandle());\n oldRoot.parent = newRoot;\n }\n // Return the new root as a convenience.\n return newRoot;\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Set up the computed minimum size.\n let minW = 0;\n let minH = 0;\n // Update the size limits for the layout tree.\n if (this._root) {\n let limits = this._root.fit(this._spacing, this._items);\n minW = limits.minWidth;\n minH = limits.minHeight;\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Bail early if there is no root layout node.\n if (!this._root) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the actual layout bounds adjusted for border and padding.\n let x = this._box.paddingTop;\n let y = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Update the geometry of the layout tree.\n this._root.update(x, y, width, height, this._spacing, this._items);\n }\n /**\n * Create a new tab bar for use by the dock layout.\n *\n * #### Notes\n * The tab bar will be attached to the parent if it exists.\n */\n _createTabBar() {\n // Create the tab bar using the renderer.\n let tabBar = this.renderer.createTabBar(this._document);\n // Enforce necessary tab bar behavior.\n tabBar.orientation = 'horizontal';\n // Attach the tab bar to the parent if possible.\n if (this.parent) {\n this.attachWidget(tabBar);\n }\n // Return the initialized tab bar.\n return tabBar;\n }\n /**\n * Create a new handle for the dock layout.\n *\n * #### Notes\n * The handle will be attached to the parent if it exists.\n */\n _createHandle() {\n // Create the handle using the renderer.\n let handle = this.renderer.createHandle();\n // Initialize the handle layout behavior.\n let style = handle.style;\n style.position = 'absolute';\n style.contain = 'strict';\n style.top = '0';\n style.left = '0';\n style.width = '0';\n style.height = '0';\n // Attach the handle to the parent if it exists.\n if (this.parent) {\n this.parent.node.appendChild(handle);\n }\n // Return the initialized handle.\n return handle;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$6;\n(function (Private) {\n /**\n * A fraction used for sizing root panels; ~= `1 / golden_ratio`.\n */\n Private.GOLDEN_RATIO = 0.618;\n /**\n * Create a box sizer with an initial size hint.\n */\n function createSizer(hint) {\n let sizer = new BoxSizer();\n sizer.sizeHint = hint;\n sizer.size = hint;\n return sizer;\n }\n Private.createSizer = createSizer;\n /**\n * Normalize an area config object and collect the visited widgets.\n */\n function normalizeAreaConfig(config, widgetSet) {\n let result;\n if (config.type === 'tab-area') {\n result = normalizeTabAreaConfig(config, widgetSet);\n }\n else {\n result = normalizeSplitAreaConfig(config, widgetSet);\n }\n return result;\n }\n Private.normalizeAreaConfig = normalizeAreaConfig;\n /**\n * Convert a normalized area config into a layout tree.\n */\n function realizeAreaConfig(config, renderer, document) {\n let node;\n if (config.type === 'tab-area') {\n node = realizeTabAreaConfig(config, renderer, document);\n }\n else {\n node = realizeSplitAreaConfig(config, renderer, document);\n }\n return node;\n }\n Private.realizeAreaConfig = realizeAreaConfig;\n /**\n * A layout node which holds the data for a tabbed area.\n */\n class TabLayoutNode {\n /**\n * Construct a new tab layout node.\n *\n * @param tabBar - The tab bar to use for the layout node.\n */\n constructor(tabBar) {\n /**\n * The parent of the layout node.\n */\n this.parent = null;\n this._top = 0;\n this._left = 0;\n this._width = 0;\n this._height = 0;\n let tabSizer = new BoxSizer();\n let widgetSizer = new BoxSizer();\n tabSizer.stretch = 0;\n widgetSizer.stretch = 1;\n this.tabBar = tabBar;\n this.sizers = [tabSizer, widgetSizer];\n }\n /**\n * The most recent value for the `top` edge of the layout box.\n */\n get top() {\n return this._top;\n }\n /**\n * The most recent value for the `left` edge of the layout box.\n */\n get left() {\n return this._left;\n }\n /**\n * The most recent value for the `width` of the layout box.\n */\n get width() {\n return this._width;\n }\n /**\n * The most recent value for the `height` of the layout box.\n */\n get height() {\n return this._height;\n }\n /**\n * Create an iterator for all widgets in the layout tree.\n */\n *iterAllWidgets() {\n yield this.tabBar;\n yield* this.iterUserWidgets();\n }\n /**\n * Create an iterator for the user widgets in the layout tree.\n */\n *iterUserWidgets() {\n for (const title of this.tabBar.titles) {\n yield title.owner;\n }\n }\n /**\n * Create an iterator for the selected widgets in the layout tree.\n */\n *iterSelectedWidgets() {\n let title = this.tabBar.currentTitle;\n if (title) {\n yield title.owner;\n }\n }\n /**\n * Create an iterator for the tab bars in the layout tree.\n */\n *iterTabBars() {\n yield this.tabBar;\n }\n /**\n * Create an iterator for the handles in the layout tree.\n */\n // eslint-disable-next-line require-yield\n *iterHandles() {\n return;\n }\n /**\n * Find the tab layout node which contains the given widget.\n */\n findTabNode(widget) {\n return this.tabBar.titles.indexOf(widget.title) !== -1 ? this : null;\n }\n /**\n * Find the split layout node which contains the given handle.\n */\n findSplitNode(handle) {\n return null;\n }\n /**\n * Find the first tab layout node in a layout tree.\n */\n findFirstTabNode() {\n return this;\n }\n /**\n * Find the tab layout node which contains the local point.\n */\n hitTestTabNodes(x, y) {\n if (x < this._left || x >= this._left + this._width) {\n return null;\n }\n if (y < this._top || y >= this._top + this._height) {\n return null;\n }\n return this;\n }\n /**\n * Create a configuration object for the layout tree.\n */\n createConfig() {\n let widgets = this.tabBar.titles.map(title => title.owner);\n let currentIndex = this.tabBar.currentIndex;\n return { type: 'tab-area', widgets, currentIndex };\n }\n /**\n * Recursively hold all of the sizes in the layout tree.\n *\n * This ignores the sizers of tab layout nodes.\n */\n holdAllSizes() {\n return;\n }\n /**\n * Fit the layout tree.\n */\n fit(spacing, items) {\n // Set up the limit variables.\n let minWidth = 0;\n let minHeight = 0;\n let maxWidth = Infinity;\n let maxHeight = Infinity;\n // Lookup the tab bar layout item.\n let tabBarItem = items.get(this.tabBar);\n // Lookup the widget layout item.\n let current = this.tabBar.currentTitle;\n let widgetItem = current ? items.get(current.owner) : undefined;\n // Lookup the tab bar and widget sizers.\n let [tabBarSizer, widgetSizer] = this.sizers;\n // Update the tab bar limits.\n if (tabBarItem) {\n tabBarItem.fit();\n }\n // Update the widget limits.\n if (widgetItem) {\n widgetItem.fit();\n }\n // Update the results and sizer for the tab bar.\n if (tabBarItem && !tabBarItem.isHidden) {\n minWidth = Math.max(minWidth, tabBarItem.minWidth);\n minHeight += tabBarItem.minHeight;\n tabBarSizer.minSize = tabBarItem.minHeight;\n tabBarSizer.maxSize = tabBarItem.maxHeight;\n }\n else {\n tabBarSizer.minSize = 0;\n tabBarSizer.maxSize = 0;\n }\n // Update the results and sizer for the current widget.\n if (widgetItem && !widgetItem.isHidden) {\n minWidth = Math.max(minWidth, widgetItem.minWidth);\n minHeight += widgetItem.minHeight;\n widgetSizer.minSize = widgetItem.minHeight;\n widgetSizer.maxSize = Infinity;\n }\n else {\n widgetSizer.minSize = 0;\n widgetSizer.maxSize = Infinity;\n }\n // Return the computed size limits for the layout node.\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n /**\n * Update the layout tree.\n */\n update(left, top, width, height, spacing, items) {\n // Update the layout box values.\n this._top = top;\n this._left = left;\n this._width = width;\n this._height = height;\n // Lookup the tab bar layout item.\n let tabBarItem = items.get(this.tabBar);\n // Lookup the widget layout item.\n let current = this.tabBar.currentTitle;\n let widgetItem = current ? items.get(current.owner) : undefined;\n // Distribute the layout space to the sizers.\n BoxEngine.calc(this.sizers, height);\n // Update the tab bar item using the computed size.\n if (tabBarItem && !tabBarItem.isHidden) {\n let size = this.sizers[0].size;\n tabBarItem.update(left, top, width, size);\n top += size;\n }\n // Layout the widget using the computed size.\n if (widgetItem && !widgetItem.isHidden) {\n let size = this.sizers[1].size;\n widgetItem.update(left, top, width, size);\n }\n }\n }\n Private.TabLayoutNode = TabLayoutNode;\n /**\n * A layout node which holds the data for a split area.\n */\n class SplitLayoutNode {\n /**\n * Construct a new split layout node.\n *\n * @param orientation - The orientation of the node.\n */\n constructor(orientation) {\n /**\n * The parent of the layout node.\n */\n this.parent = null;\n /**\n * Whether the sizers have been normalized.\n */\n this.normalized = false;\n /**\n * The child nodes for the split node.\n */\n this.children = [];\n /**\n * The box sizers for the layout children.\n */\n this.sizers = [];\n /**\n * The handles for the layout children.\n */\n this.handles = [];\n this.orientation = orientation;\n }\n /**\n * Create an iterator for all widgets in the layout tree.\n */\n *iterAllWidgets() {\n for (const child of this.children) {\n yield* child.iterAllWidgets();\n }\n }\n /**\n * Create an iterator for the user widgets in the layout tree.\n */\n *iterUserWidgets() {\n for (const child of this.children) {\n yield* child.iterUserWidgets();\n }\n }\n /**\n * Create an iterator for the selected widgets in the layout tree.\n */\n *iterSelectedWidgets() {\n for (const child of this.children) {\n yield* child.iterSelectedWidgets();\n }\n }\n /**\n * Create an iterator for the tab bars in the layout tree.\n */\n *iterTabBars() {\n for (const child of this.children) {\n yield* child.iterTabBars();\n }\n }\n /**\n * Create an iterator for the handles in the layout tree.\n */\n *iterHandles() {\n yield* this.handles;\n for (const child of this.children) {\n yield* child.iterHandles();\n }\n }\n /**\n * Find the tab layout node which contains the given widget.\n */\n findTabNode(widget) {\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let result = this.children[i].findTabNode(widget);\n if (result) {\n return result;\n }\n }\n return null;\n }\n /**\n * Find the split layout node which contains the given handle.\n */\n findSplitNode(handle) {\n let index = this.handles.indexOf(handle);\n if (index !== -1) {\n return { index, node: this };\n }\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let result = this.children[i].findSplitNode(handle);\n if (result) {\n return result;\n }\n }\n return null;\n }\n /**\n * Find the first tab layout node in a layout tree.\n */\n findFirstTabNode() {\n if (this.children.length === 0) {\n return null;\n }\n return this.children[0].findFirstTabNode();\n }\n /**\n * Find the tab layout node which contains the local point.\n */\n hitTestTabNodes(x, y) {\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let result = this.children[i].hitTestTabNodes(x, y);\n if (result) {\n return result;\n }\n }\n return null;\n }\n /**\n * Create a configuration object for the layout tree.\n */\n createConfig() {\n let orientation = this.orientation;\n let sizes = this.createNormalizedSizes();\n let children = this.children.map(child => child.createConfig());\n return { type: 'split-area', orientation, children, sizes };\n }\n /**\n * Sync the visibility and orientation of the handles.\n */\n syncHandles() {\n this.handles.forEach((handle, i) => {\n handle.setAttribute('data-orientation', this.orientation);\n if (i === this.handles.length - 1) {\n handle.classList.add('lm-mod-hidden');\n }\n else {\n handle.classList.remove('lm-mod-hidden');\n }\n });\n }\n /**\n * Hold the current sizes of the box sizers.\n *\n * This sets the size hint of each sizer to its current size.\n */\n holdSizes() {\n for (const sizer of this.sizers) {\n sizer.sizeHint = sizer.size;\n }\n }\n /**\n * Recursively hold all of the sizes in the layout tree.\n *\n * This ignores the sizers of tab layout nodes.\n */\n holdAllSizes() {\n for (const child of this.children) {\n child.holdAllSizes();\n }\n this.holdSizes();\n }\n /**\n * Normalize the sizes of the split layout node.\n */\n normalizeSizes() {\n // Bail early if the sizers are empty.\n let n = this.sizers.length;\n if (n === 0) {\n return;\n }\n // Hold the current sizes of the sizers.\n this.holdSizes();\n // Compute the sum of the sizes.\n let sum = this.sizers.reduce((v, sizer) => v + sizer.sizeHint, 0);\n // Normalize the sizes based on the sum.\n if (sum === 0) {\n for (const sizer of this.sizers) {\n sizer.size = sizer.sizeHint = 1 / n;\n }\n }\n else {\n for (const sizer of this.sizers) {\n sizer.size = sizer.sizeHint /= sum;\n }\n }\n // Mark the sizes as normalized.\n this.normalized = true;\n }\n /**\n * Snap the normalized sizes of the split layout node.\n */\n createNormalizedSizes() {\n // Bail early if the sizers are empty.\n let n = this.sizers.length;\n if (n === 0) {\n return [];\n }\n // Grab the current sizes of the sizers.\n let sizes = this.sizers.map(sizer => sizer.size);\n // Compute the sum of the sizes.\n let sum = sizes.reduce((v, size) => v + size, 0);\n // Normalize the sizes based on the sum.\n if (sum === 0) {\n for (let i = sizes.length - 1; i > -1; i--) {\n sizes[i] = 1 / n;\n }\n }\n else {\n for (let i = sizes.length - 1; i > -1; i--) {\n sizes[i] /= sum;\n }\n }\n // Return the normalized sizes.\n return sizes;\n }\n /**\n * Fit the layout tree.\n */\n fit(spacing, items) {\n // Compute the required fixed space.\n let horizontal = this.orientation === 'horizontal';\n let fixed = Math.max(0, this.children.length - 1) * spacing;\n // Set up the limit variables.\n let minWidth = horizontal ? fixed : 0;\n let minHeight = horizontal ? 0 : fixed;\n let maxWidth = Infinity;\n let maxHeight = Infinity;\n // Fit the children and update the limits.\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let limits = this.children[i].fit(spacing, items);\n if (horizontal) {\n minHeight = Math.max(minHeight, limits.minHeight);\n minWidth += limits.minWidth;\n this.sizers[i].minSize = limits.minWidth;\n }\n else {\n minWidth = Math.max(minWidth, limits.minWidth);\n minHeight += limits.minHeight;\n this.sizers[i].minSize = limits.minHeight;\n }\n }\n // Return the computed limits for the layout node.\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n /**\n * Update the layout tree.\n */\n update(left, top, width, height, spacing, items) {\n // Compute the available layout space.\n let horizontal = this.orientation === 'horizontal';\n let fixed = Math.max(0, this.children.length - 1) * spacing;\n let space = Math.max(0, (horizontal ? width : height) - fixed);\n // De-normalize the sizes if needed.\n if (this.normalized) {\n for (const sizer of this.sizers) {\n sizer.sizeHint *= space;\n }\n this.normalized = false;\n }\n // Distribute the layout space to the sizers.\n BoxEngine.calc(this.sizers, space);\n // Update the geometry of the child nodes and handles.\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let child = this.children[i];\n let size = this.sizers[i].size;\n let handleStyle = this.handles[i].style;\n if (horizontal) {\n child.update(left, top, size, height, spacing, items);\n left += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${spacing}px`;\n handleStyle.height = `${height}px`;\n left += spacing;\n }\n else {\n child.update(left, top, width, size, spacing, items);\n top += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${width}px`;\n handleStyle.height = `${spacing}px`;\n top += spacing;\n }\n }\n }\n }\n Private.SplitLayoutNode = SplitLayoutNode;\n function addAria(widget, tabBar) {\n widget.node.setAttribute('role', 'tabpanel');\n let renderer = tabBar.renderer;\n if (renderer instanceof TabBar.Renderer) {\n let tabId = renderer.createTabKey({\n title: widget.title,\n current: false,\n zIndex: 0\n });\n widget.node.setAttribute('aria-labelledby', tabId);\n }\n }\n Private.addAria = addAria;\n function removeAria(widget) {\n widget.node.removeAttribute('role');\n widget.node.removeAttribute('aria-labelledby');\n }\n Private.removeAria = removeAria;\n /**\n * Normalize a tab area config and collect the visited widgets.\n */\n function normalizeTabAreaConfig(config, widgetSet) {\n // Bail early if there is no content.\n if (config.widgets.length === 0) {\n return null;\n }\n // Setup the filtered widgets array.\n let widgets = [];\n // Filter the config for unique widgets.\n for (const widget of config.widgets) {\n if (!widgetSet.has(widget)) {\n widgetSet.add(widget);\n widgets.push(widget);\n }\n }\n // Bail if there are no effective widgets.\n if (widgets.length === 0) {\n return null;\n }\n // Normalize the current index.\n let index = config.currentIndex;\n if (index !== -1 && (index < 0 || index >= widgets.length)) {\n index = 0;\n }\n // Return a normalized config object.\n return { type: 'tab-area', widgets, currentIndex: index };\n }\n /**\n * Normalize a split area config and collect the visited widgets.\n */\n function normalizeSplitAreaConfig(config, widgetSet) {\n // Set up the result variables.\n let orientation = config.orientation;\n let children = [];\n let sizes = [];\n // Normalize the config children.\n for (let i = 0, n = config.children.length; i < n; ++i) {\n // Normalize the child config.\n let child = normalizeAreaConfig(config.children[i], widgetSet);\n // Ignore an empty child.\n if (!child) {\n continue;\n }\n // Add the child or hoist its content as appropriate.\n if (child.type === 'tab-area' || child.orientation !== orientation) {\n children.push(child);\n sizes.push(Math.abs(config.sizes[i] || 0));\n }\n else {\n children.push(...child.children);\n sizes.push(...child.sizes);\n }\n }\n // Bail if there are no effective children.\n if (children.length === 0) {\n return null;\n }\n // If there is only one effective child, return that child.\n if (children.length === 1) {\n return children[0];\n }\n // Return a normalized config object.\n return { type: 'split-area', orientation, children, sizes };\n }\n /**\n * Convert a normalized tab area config into a layout tree.\n */\n function realizeTabAreaConfig(config, renderer, document) {\n // Create the tab bar for the layout node.\n let tabBar = renderer.createTabBar(document);\n // Hide each widget and add it to the tab bar.\n for (const widget of config.widgets) {\n widget.hide();\n tabBar.addTab(widget.title);\n Private.addAria(widget, tabBar);\n }\n // Set the current index of the tab bar.\n tabBar.currentIndex = config.currentIndex;\n // Return the new tab layout node.\n return new TabLayoutNode(tabBar);\n }\n /**\n * Convert a normalized split area config into a layout tree.\n */\n function realizeSplitAreaConfig(config, renderer, document) {\n // Create the split layout node.\n let node = new SplitLayoutNode(config.orientation);\n // Add each child to the layout node.\n config.children.forEach((child, i) => {\n // Create the child data for the layout node.\n let childNode = realizeAreaConfig(child, renderer, document);\n let sizer = createSizer(config.sizes[i]);\n let handle = renderer.createHandle();\n // Add the child data to the layout node.\n node.children.push(childNode);\n node.handles.push(handle);\n node.sizers.push(sizer);\n // Update the parent for the child node.\n childNode.parent = node;\n });\n // Synchronize the handle state for the layout node.\n node.syncHandles();\n // Normalize the sizes for the layout node.\n node.normalizeSizes();\n // Return the new layout node.\n return node;\n }\n})(Private$6 || (Private$6 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which provides a flexible docking area for widgets.\n */\nclass DockPanel extends Widget {\n /**\n * Construct a new dock panel.\n *\n * @param options - The options for initializing the panel.\n */\n constructor(options = {}) {\n super();\n this._drag = null;\n this._tabsMovable = true;\n this._tabsConstrained = false;\n this._addButtonEnabled = false;\n this._pressData = null;\n this._layoutModified = new Signal(this);\n this._addRequested = new Signal(this);\n this.addClass('lm-DockPanel');\n this._document = options.document || document;\n this._mode = options.mode || 'multiple-document';\n this._renderer = options.renderer || DockPanel.defaultRenderer;\n this._edges = options.edges || Private$5.DEFAULT_EDGES;\n if (options.tabsMovable !== undefined) {\n this._tabsMovable = options.tabsMovable;\n }\n if (options.tabsConstrained !== undefined) {\n this._tabsConstrained = options.tabsConstrained;\n }\n if (options.addButtonEnabled !== undefined) {\n this._addButtonEnabled = options.addButtonEnabled;\n }\n // Toggle the CSS mode attribute.\n this.dataset['mode'] = this._mode;\n // Create the delegate renderer for the layout.\n let renderer = {\n createTabBar: () => this._createTabBar(),\n createHandle: () => this._createHandle()\n };\n // Set up the dock layout for the panel.\n this.layout = new DockLayout({\n document: this._document,\n renderer,\n spacing: options.spacing,\n hiddenMode: options.hiddenMode\n });\n // Set up the overlay drop indicator.\n this.overlay = options.overlay || new DockPanel.Overlay();\n this.node.appendChild(this.overlay.node);\n }\n /**\n * Dispose of the resources held by the panel.\n */\n dispose() {\n // Ensure the mouse is released.\n this._releaseMouse();\n // Hide the overlay.\n this.overlay.hide(0);\n // Cancel a drag if one is in progress.\n if (this._drag) {\n this._drag.dispose();\n }\n // Dispose of the base class.\n super.dispose();\n }\n /**\n * The method for hiding widgets.\n */\n get hiddenMode() {\n return this.layout.hiddenMode;\n }\n /**\n * Set the method for hiding widgets.\n */\n set hiddenMode(v) {\n this.layout.hiddenMode = v;\n }\n /**\n * A signal emitted when the layout configuration is modified.\n *\n * #### Notes\n * This signal is emitted whenever the current layout configuration\n * may have changed.\n *\n * This signal is emitted asynchronously in a collapsed fashion, so\n * that multiple synchronous modifications results in only a single\n * emit of the signal.\n */\n get layoutModified() {\n return this._layoutModified;\n }\n /**\n * A signal emitted when the add button on a tab bar is clicked.\n *\n */\n get addRequested() {\n return this._addRequested;\n }\n /**\n * The renderer used by the dock panel.\n */\n get renderer() {\n return this.layout.renderer;\n }\n /**\n * Get the spacing between the widgets.\n */\n get spacing() {\n return this.layout.spacing;\n }\n /**\n * Set the spacing between the widgets.\n */\n set spacing(value) {\n this.layout.spacing = value;\n }\n /**\n * Get the mode for the dock panel.\n */\n get mode() {\n return this._mode;\n }\n /**\n * Set the mode for the dock panel.\n *\n * #### Notes\n * Changing the mode is a destructive operation with respect to the\n * panel's layout configuration. If layout state must be preserved,\n * save the current layout config before changing the mode.\n */\n set mode(value) {\n // Bail early if the mode does not change.\n if (this._mode === value) {\n return;\n }\n // Update the internal mode.\n this._mode = value;\n // Toggle the CSS mode attribute.\n this.dataset['mode'] = value;\n // Get the layout for the panel.\n let layout = this.layout;\n // Configure the layout for the specified mode.\n switch (value) {\n case 'multiple-document':\n for (const tabBar of layout.tabBars()) {\n tabBar.show();\n }\n break;\n case 'single-document':\n layout.restoreLayout(Private$5.createSingleDocumentConfig(this));\n break;\n default:\n throw 'unreachable';\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Whether the tabs can be dragged / moved at runtime.\n */\n get tabsMovable() {\n return this._tabsMovable;\n }\n /**\n * Enable / Disable draggable / movable tabs.\n */\n set tabsMovable(value) {\n this._tabsMovable = value;\n for (const tabBar of this.tabBars()) {\n tabBar.tabsMovable = value;\n }\n }\n /**\n * Whether the tabs are constrained to their source dock panel\n */\n get tabsConstrained() {\n return this._tabsConstrained;\n }\n /**\n * Constrain/Allow tabs to be dragged outside of this dock panel\n */\n set tabsConstrained(value) {\n this._tabsConstrained = value;\n }\n /**\n * Whether the add buttons for each tab bar are enabled.\n */\n get addButtonEnabled() {\n return this._addButtonEnabled;\n }\n /**\n * Set whether the add buttons for each tab bar are enabled.\n */\n set addButtonEnabled(value) {\n this._addButtonEnabled = value;\n for (const tabBar of this.tabBars()) {\n tabBar.addButtonEnabled = value;\n }\n }\n /**\n * Whether the dock panel is empty.\n */\n get isEmpty() {\n return this.layout.isEmpty;\n }\n /**\n * Create an iterator over the user widgets in the panel.\n *\n * @returns A new iterator over the user widgets in the panel.\n *\n * #### Notes\n * This iterator does not include the generated tab bars.\n */\n *widgets() {\n yield* this.layout.widgets();\n }\n /**\n * Create an iterator over the selected widgets in the panel.\n *\n * @returns A new iterator over the selected user widgets.\n *\n * #### Notes\n * This iterator yields the widgets corresponding to the current tab\n * of each tab bar in the panel.\n */\n *selectedWidgets() {\n yield* this.layout.selectedWidgets();\n }\n /**\n * Create an iterator over the tab bars in the panel.\n *\n * @returns A new iterator over the tab bars in the panel.\n *\n * #### Notes\n * This iterator does not include the user widgets.\n */\n *tabBars() {\n yield* this.layout.tabBars();\n }\n /**\n * Create an iterator over the handles in the panel.\n *\n * @returns A new iterator over the handles in the panel.\n */\n *handles() {\n yield* this.layout.handles();\n }\n /**\n * Select a specific widget in the dock panel.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * This will make the widget the current widget in its tab area.\n */\n selectWidget(widget) {\n // Find the tab bar which contains the widget.\n let tabBar = find(this.tabBars(), bar => {\n return bar.titles.indexOf(widget.title) !== -1;\n });\n // Throw an error if no tab bar is found.\n if (!tabBar) {\n throw new Error('Widget is not contained in the dock panel.');\n }\n // Ensure the widget is the current widget.\n tabBar.currentTitle = widget.title;\n }\n /**\n * Activate a specified widget in the dock panel.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * This will select and activate the given widget.\n */\n activateWidget(widget) {\n this.selectWidget(widget);\n widget.activate();\n }\n /**\n * Save the current layout configuration of the dock panel.\n *\n * @returns A new config object for the current layout state.\n *\n * #### Notes\n * The return value can be provided to the `restoreLayout` method\n * in order to restore the layout to its current configuration.\n */\n saveLayout() {\n return this.layout.saveLayout();\n }\n /**\n * Restore the layout to a previously saved configuration.\n *\n * @param config - The layout configuration to restore.\n *\n * #### Notes\n * Widgets which currently belong to the layout but which are not\n * contained in the config will be unparented.\n *\n * The dock panel automatically reverts to `'multiple-document'`\n * mode when a layout config is restored.\n */\n restoreLayout(config) {\n // Reset the mode.\n this._mode = 'multiple-document';\n // Restore the layout.\n this.layout.restoreLayout(config);\n // Flush the message loop on IE and Edge to prevent flicker.\n if (Platform.IS_EDGE || Platform.IS_IE) {\n MessageLoop.flush();\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Add a widget to the dock panel.\n *\n * @param widget - The widget to add to the dock panel.\n *\n * @param options - The additional options for adding the widget.\n *\n * #### Notes\n * If the panel is in single document mode, the options are ignored\n * and the widget is always added as tab in the hidden tab bar.\n */\n addWidget(widget, options = {}) {\n // Add the widget to the layout.\n if (this._mode === 'single-document') {\n this.layout.addWidget(widget);\n }\n else {\n this.layout.addWidget(widget, options);\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Process a message sent to the widget.\n *\n * @param msg - The message sent to the widget.\n */\n processMessage(msg) {\n if (msg.type === 'layout-modified') {\n this._layoutModified.emit(undefined);\n }\n else {\n super.processMessage(msg);\n }\n }\n /**\n * Handle the DOM events for the dock panel.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the panel's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'lm-dragenter':\n this._evtDragEnter(event);\n break;\n case 'lm-dragleave':\n this._evtDragLeave(event);\n break;\n case 'lm-dragover':\n this._evtDragOver(event);\n break;\n case 'lm-drop':\n this._evtDrop(event);\n break;\n case 'pointerdown':\n this._evtPointerDown(event);\n break;\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('lm-dragenter', this);\n this.node.addEventListener('lm-dragleave', this);\n this.node.addEventListener('lm-dragover', this);\n this.node.addEventListener('lm-drop', this);\n this.node.addEventListener('pointerdown', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('lm-dragenter', this);\n this.node.removeEventListener('lm-dragleave', this);\n this.node.removeEventListener('lm-dragover', this);\n this.node.removeEventListener('lm-drop', this);\n this.node.removeEventListener('pointerdown', this);\n this._releaseMouse();\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n // Ignore the generated tab bars.\n if (Private$5.isGeneratedTabBarProperty.get(msg.child)) {\n return;\n }\n // Add the widget class to the child.\n msg.child.addClass('lm-DockPanel-widget');\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n // Ignore the generated tab bars.\n if (Private$5.isGeneratedTabBarProperty.get(msg.child)) {\n return;\n }\n // Remove the widget class from the child.\n msg.child.removeClass('lm-DockPanel-widget');\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Handle the `'lm-dragenter'` event for the dock panel.\n */\n _evtDragEnter(event) {\n // If the factory mime type is present, mark the event as\n // handled in order to get the rest of the drag events.\n if (event.mimeData.hasData('application/vnd.lumino.widget-factory')) {\n event.preventDefault();\n event.stopPropagation();\n }\n }\n /**\n * Handle the `'lm-dragleave'` event for the dock panel.\n */\n _evtDragLeave(event) {\n // Mark the event as handled.\n event.preventDefault();\n if (this._tabsConstrained && event.source !== this)\n return;\n event.stopPropagation();\n // The new target might be a descendant, so we might still handle the drop.\n // Hide asynchronously so that if a lm-dragover event bubbles up to us, the\n // hide is cancelled by the lm-dragover handler's show overlay logic.\n this.overlay.hide(1);\n }\n /**\n * Handle the `'lm-dragover'` event for the dock panel.\n */\n _evtDragOver(event) {\n // Mark the event as handled.\n event.preventDefault();\n // Show the drop indicator overlay and update the drop\n // action based on the drop target zone under the mouse.\n if ((this._tabsConstrained && event.source !== this) ||\n this._showOverlay(event.clientX, event.clientY) === 'invalid') {\n event.dropAction = 'none';\n }\n else {\n event.stopPropagation();\n event.dropAction = event.proposedAction;\n }\n }\n /**\n * Handle the `'lm-drop'` event for the dock panel.\n */\n _evtDrop(event) {\n // Mark the event as handled.\n event.preventDefault();\n // Hide the drop indicator overlay.\n this.overlay.hide(0);\n // Bail if the proposed action is to do nothing.\n if (event.proposedAction === 'none') {\n event.dropAction = 'none';\n return;\n }\n // Find the drop target under the mouse.\n let { clientX, clientY } = event;\n let { zone, target } = Private$5.findDropTarget(this, clientX, clientY, this._edges);\n // Bail if the drop zone is invalid.\n if ((this._tabsConstrained && event.source !== this) ||\n zone === 'invalid') {\n event.dropAction = 'none';\n return;\n }\n // Bail if the factory mime type has invalid data.\n let mimeData = event.mimeData;\n let factory = mimeData.getData('application/vnd.lumino.widget-factory');\n if (typeof factory !== 'function') {\n event.dropAction = 'none';\n return;\n }\n // Bail if the factory does not produce a widget.\n let widget = factory();\n if (!(widget instanceof Widget)) {\n event.dropAction = 'none';\n return;\n }\n // Bail if the widget is an ancestor of the dock panel.\n if (widget.contains(this)) {\n event.dropAction = 'none';\n return;\n }\n // Find the reference widget for the drop target.\n let ref = target ? Private$5.getDropRef(target.tabBar) : null;\n // Add the widget according to the indicated drop zone.\n switch (zone) {\n case 'root-all':\n this.addWidget(widget);\n break;\n case 'root-top':\n this.addWidget(widget, { mode: 'split-top' });\n break;\n case 'root-left':\n this.addWidget(widget, { mode: 'split-left' });\n break;\n case 'root-right':\n this.addWidget(widget, { mode: 'split-right' });\n break;\n case 'root-bottom':\n this.addWidget(widget, { mode: 'split-bottom' });\n break;\n case 'widget-all':\n this.addWidget(widget, { mode: 'tab-after', ref });\n break;\n case 'widget-top':\n this.addWidget(widget, { mode: 'split-top', ref });\n break;\n case 'widget-left':\n this.addWidget(widget, { mode: 'split-left', ref });\n break;\n case 'widget-right':\n this.addWidget(widget, { mode: 'split-right', ref });\n break;\n case 'widget-bottom':\n this.addWidget(widget, { mode: 'split-bottom', ref });\n break;\n case 'widget-tab':\n this.addWidget(widget, { mode: 'tab-after', ref });\n break;\n default:\n throw 'unreachable';\n }\n // Accept the proposed drop action.\n event.dropAction = event.proposedAction;\n // Stop propagation if we have not bailed so far.\n event.stopPropagation();\n // Activate the dropped widget.\n this.activateWidget(widget);\n }\n /**\n * Handle the `'keydown'` event for the dock panel.\n */\n _evtKeyDown(event) {\n // Stop input events during drag.\n event.preventDefault();\n event.stopPropagation();\n // Release the mouse if `Escape` is pressed.\n if (event.keyCode === 27) {\n // Finalize the mouse release.\n this._releaseMouse();\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n }\n /**\n * Handle the `'pointerdown'` event for the dock panel.\n */\n _evtPointerDown(event) {\n // Do nothing if the left mouse button is not pressed.\n if (event.button !== 0) {\n return;\n }\n // Find the handle which contains the mouse target, if any.\n let layout = this.layout;\n let target = event.target;\n let handle = find(layout.handles(), handle => handle.contains(target));\n if (!handle) {\n return;\n }\n // Stop the event when a handle is pressed.\n event.preventDefault();\n event.stopPropagation();\n // Add the extra document listeners.\n this._document.addEventListener('keydown', this, true);\n this._document.addEventListener('pointerup', this, true);\n this._document.addEventListener('pointermove', this, true);\n this._document.addEventListener('contextmenu', this, true);\n // Compute the offset deltas for the handle press.\n let rect = handle.getBoundingClientRect();\n let deltaX = event.clientX - rect.left;\n let deltaY = event.clientY - rect.top;\n // Override the cursor and store the press data.\n let style = window.getComputedStyle(handle);\n let override = Drag.overrideCursor(style.cursor, this._document);\n this._pressData = { handle, deltaX, deltaY, override };\n }\n /**\n * Handle the `'pointermove'` event for the dock panel.\n */\n _evtPointerMove(event) {\n // Bail early if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Stop the event when dragging a handle.\n event.preventDefault();\n event.stopPropagation();\n // Compute the desired offset position for the handle.\n let rect = this.node.getBoundingClientRect();\n let xPos = event.clientX - rect.left - this._pressData.deltaX;\n let yPos = event.clientY - rect.top - this._pressData.deltaY;\n // Set the handle as close to the desired position as possible.\n let layout = this.layout;\n layout.moveHandle(this._pressData.handle, xPos, yPos);\n }\n /**\n * Handle the `'pointerup'` event for the dock panel.\n */\n _evtPointerUp(event) {\n // Do nothing if the left mouse button is not released.\n if (event.button !== 0) {\n return;\n }\n // Stop the event when releasing a handle.\n event.preventDefault();\n event.stopPropagation();\n // Finalize the mouse release.\n this._releaseMouse();\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Release the mouse grab for the dock panel.\n */\n _releaseMouse() {\n // Bail early if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Clear the override cursor.\n this._pressData.override.dispose();\n this._pressData = null;\n // Remove the extra document listeners.\n this._document.removeEventListener('keydown', this, true);\n this._document.removeEventListener('pointerup', this, true);\n this._document.removeEventListener('pointermove', this, true);\n this._document.removeEventListener('contextmenu', this, true);\n }\n /**\n * Show the overlay indicator at the given client position.\n *\n * Returns the drop zone at the specified client position.\n *\n * #### Notes\n * If the position is not over a valid zone, the overlay is hidden.\n */\n _showOverlay(clientX, clientY) {\n // Find the dock target for the given client position.\n let { zone, target } = Private$5.findDropTarget(this, clientX, clientY, this._edges);\n // If the drop zone is invalid, hide the overlay and bail.\n if (zone === 'invalid') {\n this.overlay.hide(100);\n return zone;\n }\n // Setup the variables needed to compute the overlay geometry.\n let top;\n let left;\n let right;\n let bottom;\n let box = ElementExt.boxSizing(this.node); // TODO cache this?\n let rect = this.node.getBoundingClientRect();\n // Compute the overlay geometry based on the dock zone.\n switch (zone) {\n case 'root-all':\n top = box.paddingTop;\n left = box.paddingLeft;\n right = box.paddingRight;\n bottom = box.paddingBottom;\n break;\n case 'root-top':\n top = box.paddingTop;\n left = box.paddingLeft;\n right = box.paddingRight;\n bottom = rect.height * Private$5.GOLDEN_RATIO;\n break;\n case 'root-left':\n top = box.paddingTop;\n left = box.paddingLeft;\n right = rect.width * Private$5.GOLDEN_RATIO;\n bottom = box.paddingBottom;\n break;\n case 'root-right':\n top = box.paddingTop;\n left = rect.width * Private$5.GOLDEN_RATIO;\n right = box.paddingRight;\n bottom = box.paddingBottom;\n break;\n case 'root-bottom':\n top = rect.height * Private$5.GOLDEN_RATIO;\n left = box.paddingLeft;\n right = box.paddingRight;\n bottom = box.paddingBottom;\n break;\n case 'widget-all':\n top = target.top;\n left = target.left;\n right = target.right;\n bottom = target.bottom;\n break;\n case 'widget-top':\n top = target.top;\n left = target.left;\n right = target.right;\n bottom = target.bottom + target.height / 2;\n break;\n case 'widget-left':\n top = target.top;\n left = target.left;\n right = target.right + target.width / 2;\n bottom = target.bottom;\n break;\n case 'widget-right':\n top = target.top;\n left = target.left + target.width / 2;\n right = target.right;\n bottom = target.bottom;\n break;\n case 'widget-bottom':\n top = target.top + target.height / 2;\n left = target.left;\n right = target.right;\n bottom = target.bottom;\n break;\n case 'widget-tab': {\n const tabHeight = target.tabBar.node.getBoundingClientRect().height;\n top = target.top;\n left = target.left;\n right = target.right;\n bottom = target.bottom + target.height - tabHeight;\n break;\n }\n default:\n throw 'unreachable';\n }\n // Show the overlay with the computed geometry.\n this.overlay.show({ top, left, right, bottom });\n // Finally, return the computed drop zone.\n return zone;\n }\n /**\n * Create a new tab bar for use by the panel.\n */\n _createTabBar() {\n // Create the tab bar.\n let tabBar = this._renderer.createTabBar(this._document);\n // Set the generated tab bar property for the tab bar.\n Private$5.isGeneratedTabBarProperty.set(tabBar, true);\n // Hide the tab bar when in single document mode.\n if (this._mode === 'single-document') {\n tabBar.hide();\n }\n // Enforce necessary tab bar behavior.\n // TODO do we really want to enforce *all* of these?\n tabBar.tabsMovable = this._tabsMovable;\n tabBar.allowDeselect = false;\n tabBar.addButtonEnabled = this._addButtonEnabled;\n tabBar.removeBehavior = 'select-previous-tab';\n tabBar.insertBehavior = 'select-tab-if-needed';\n // Connect the signal handlers for the tab bar.\n tabBar.tabMoved.connect(this._onTabMoved, this);\n tabBar.currentChanged.connect(this._onCurrentChanged, this);\n tabBar.tabCloseRequested.connect(this._onTabCloseRequested, this);\n tabBar.tabDetachRequested.connect(this._onTabDetachRequested, this);\n tabBar.tabActivateRequested.connect(this._onTabActivateRequested, this);\n tabBar.addRequested.connect(this._onTabAddRequested, this);\n // Return the initialized tab bar.\n return tabBar;\n }\n /**\n * Create a new handle for use by the panel.\n */\n _createHandle() {\n return this._renderer.createHandle();\n }\n /**\n * Handle the `tabMoved` signal from a tab bar.\n */\n _onTabMoved() {\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Handle the `currentChanged` signal from a tab bar.\n */\n _onCurrentChanged(sender, args) {\n // Extract the previous and current title from the args.\n let { previousTitle, currentTitle } = args;\n // Hide the previous widget.\n if (previousTitle) {\n previousTitle.owner.hide();\n }\n // Show the current widget.\n if (currentTitle) {\n currentTitle.owner.show();\n }\n // Flush the message loop on IE and Edge to prevent flicker.\n if (Platform.IS_EDGE || Platform.IS_IE) {\n MessageLoop.flush();\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Handle the `addRequested` signal from a tab bar.\n */\n _onTabAddRequested(sender) {\n this._addRequested.emit(sender);\n }\n /**\n * Handle the `tabActivateRequested` signal from a tab bar.\n */\n _onTabActivateRequested(sender, args) {\n args.title.owner.activate();\n }\n /**\n * Handle the `tabCloseRequested` signal from a tab bar.\n */\n _onTabCloseRequested(sender, args) {\n args.title.owner.close();\n }\n /**\n * Handle the `tabDetachRequested` signal from a tab bar.\n */\n _onTabDetachRequested(sender, args) {\n // Do nothing if a drag is already in progress.\n if (this._drag) {\n return;\n }\n // Release the tab bar's hold on the mouse.\n sender.releaseMouse();\n // Extract the data from the args.\n let { title, tab, clientX, clientY, offset } = args;\n // Setup the mime data for the drag operation.\n let mimeData = new MimeData();\n let factory = () => title.owner;\n mimeData.setData('application/vnd.lumino.widget-factory', factory);\n // Create the drag image for the drag operation.\n let dragImage = tab.cloneNode(true);\n if (offset) {\n dragImage.style.top = `-${offset.y}px`;\n dragImage.style.left = `-${offset.x}px`;\n }\n // Create the drag object to manage the drag-drop operation.\n this._drag = new Drag({\n document: this._document,\n mimeData,\n dragImage,\n proposedAction: 'move',\n supportedActions: 'move',\n source: this\n });\n // Hide the tab node in the original tab.\n tab.classList.add('lm-mod-hidden');\n let cleanup = () => {\n this._drag = null;\n tab.classList.remove('lm-mod-hidden');\n };\n // Start the drag operation and cleanup when done.\n this._drag.start(clientX, clientY).then(cleanup);\n }\n}\n/**\n * The namespace for the `DockPanel` class statics.\n */\n(function (DockPanel) {\n /**\n * A concrete implementation of `IOverlay`.\n *\n * This is the default overlay implementation for a dock panel.\n */\n class Overlay {\n /**\n * Construct a new overlay.\n */\n constructor() {\n this._timer = -1;\n this._hidden = true;\n this.node = document.createElement('div');\n this.node.classList.add('lm-DockPanel-overlay');\n this.node.classList.add('lm-mod-hidden');\n this.node.style.position = 'absolute';\n this.node.style.contain = 'strict';\n }\n /**\n * Show the overlay using the given overlay geometry.\n *\n * @param geo - The desired geometry for the overlay.\n */\n show(geo) {\n // Update the position of the overlay.\n let style = this.node.style;\n style.top = `${geo.top}px`;\n style.left = `${geo.left}px`;\n style.right = `${geo.right}px`;\n style.bottom = `${geo.bottom}px`;\n // Clear any pending hide timer.\n clearTimeout(this._timer);\n this._timer = -1;\n // If the overlay is already visible, we're done.\n if (!this._hidden) {\n return;\n }\n // Clear the hidden flag.\n this._hidden = false;\n // Finally, show the overlay.\n this.node.classList.remove('lm-mod-hidden');\n }\n /**\n * Hide the overlay node.\n *\n * @param delay - The delay (in ms) before hiding the overlay.\n * A delay value <= 0 will hide the overlay immediately.\n */\n hide(delay) {\n // Do nothing if the overlay is already hidden.\n if (this._hidden) {\n return;\n }\n // Hide immediately if the delay is <= 0.\n if (delay <= 0) {\n clearTimeout(this._timer);\n this._timer = -1;\n this._hidden = true;\n this.node.classList.add('lm-mod-hidden');\n return;\n }\n // Do nothing if a hide is already pending.\n if (this._timer !== -1) {\n return;\n }\n // Otherwise setup the hide timer.\n this._timer = window.setTimeout(() => {\n this._timer = -1;\n this._hidden = true;\n this.node.classList.add('lm-mod-hidden');\n }, delay);\n }\n }\n DockPanel.Overlay = Overlay;\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer {\n /**\n * Create a new tab bar for use with a dock panel.\n *\n * @returns A new tab bar for a dock panel.\n */\n createTabBar(document) {\n let bar = new TabBar({ document });\n bar.addClass('lm-DockPanel-tabBar');\n return bar;\n }\n /**\n * Create a new handle node for use with a dock panel.\n *\n * @returns A new handle node for a dock panel.\n */\n createHandle() {\n let handle = document.createElement('div');\n handle.className = 'lm-DockPanel-handle';\n return handle;\n }\n }\n DockPanel.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n DockPanel.defaultRenderer = new Renderer();\n})(DockPanel || (DockPanel = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$5;\n(function (Private) {\n /**\n * A fraction used for sizing root panels; ~= `1 / golden_ratio`.\n */\n Private.GOLDEN_RATIO = 0.618;\n /**\n * The default sizes for the edge drop zones, in pixels.\n */\n Private.DEFAULT_EDGES = {\n /**\n * The size of the top edge dock zone for the root panel, in pixels.\n * This is different from the others to distinguish between the top\n * tab bar and the top root zone.\n */\n top: 12,\n /**\n * The size of the edge dock zone for the root panel, in pixels.\n */\n right: 40,\n /**\n * The size of the edge dock zone for the root panel, in pixels.\n */\n bottom: 40,\n /**\n * The size of the edge dock zone for the root panel, in pixels.\n */\n left: 40\n };\n /**\n * A singleton `'layout-modified'` conflatable message.\n */\n Private.LayoutModified = new ConflatableMessage('layout-modified');\n /**\n * An attached property used to track generated tab bars.\n */\n Private.isGeneratedTabBarProperty = new AttachedProperty({\n name: 'isGeneratedTabBar',\n create: () => false\n });\n /**\n * Create a single document config for the widgets in a dock panel.\n */\n function createSingleDocumentConfig(panel) {\n // Return an empty config if the panel is empty.\n if (panel.isEmpty) {\n return { main: null };\n }\n // Get a flat array of the widgets in the panel.\n let widgets = Array.from(panel.widgets());\n // Get the first selected widget in the panel.\n let selected = panel.selectedWidgets().next().value;\n // Compute the current index for the new config.\n let currentIndex = selected ? widgets.indexOf(selected) : -1;\n // Return the single document config.\n return { main: { type: 'tab-area', widgets, currentIndex } };\n }\n Private.createSingleDocumentConfig = createSingleDocumentConfig;\n /**\n * Find the drop target at the given client position.\n */\n function findDropTarget(panel, clientX, clientY, edges) {\n // Bail if the mouse is not over the dock panel.\n if (!ElementExt.hitTest(panel.node, clientX, clientY)) {\n return { zone: 'invalid', target: null };\n }\n // Look up the layout for the panel.\n let layout = panel.layout;\n // If the layout is empty, indicate the entire root drop zone.\n if (layout.isEmpty) {\n return { zone: 'root-all', target: null };\n }\n // Test the edge zones when in multiple document mode.\n if (panel.mode === 'multiple-document') {\n // Get the client rect for the dock panel.\n let panelRect = panel.node.getBoundingClientRect();\n // Compute the distance to each edge of the panel.\n let pl = clientX - panelRect.left + 1;\n let pt = clientY - panelRect.top + 1;\n let pr = panelRect.right - clientX;\n let pb = panelRect.bottom - clientY;\n // Find the minimum distance to an edge.\n let pd = Math.min(pt, pr, pb, pl);\n // Return a root zone if the mouse is within an edge.\n switch (pd) {\n case pt:\n if (pt < edges.top) {\n return { zone: 'root-top', target: null };\n }\n break;\n case pr:\n if (pr < edges.right) {\n return { zone: 'root-right', target: null };\n }\n break;\n case pb:\n if (pb < edges.bottom) {\n return { zone: 'root-bottom', target: null };\n }\n break;\n case pl:\n if (pl < edges.left) {\n return { zone: 'root-left', target: null };\n }\n break;\n default:\n throw 'unreachable';\n }\n }\n // Hit test the dock layout at the given client position.\n let target = layout.hitTestTabAreas(clientX, clientY);\n // Bail if no target area was found.\n if (!target) {\n return { zone: 'invalid', target: null };\n }\n // Return the whole tab area when in single document mode.\n if (panel.mode === 'single-document') {\n return { zone: 'widget-all', target };\n }\n // Compute the distance to each edge of the tab area.\n let al = target.x - target.left + 1;\n let at = target.y - target.top + 1;\n let ar = target.left + target.width - target.x;\n let ab = target.top + target.height - target.y;\n const tabHeight = target.tabBar.node.getBoundingClientRect().height;\n if (at < tabHeight) {\n return { zone: 'widget-tab', target };\n }\n // Get the X and Y edge sizes for the area.\n let rx = Math.round(target.width / 3);\n let ry = Math.round(target.height / 3);\n // If the mouse is not within an edge, indicate the entire area.\n if (al > rx && ar > rx && at > ry && ab > ry) {\n return { zone: 'widget-all', target };\n }\n // Scale the distances by the slenderness ratio.\n al /= rx;\n at /= ry;\n ar /= rx;\n ab /= ry;\n // Find the minimum distance to the area edge.\n let ad = Math.min(al, at, ar, ab);\n // Find the widget zone for the area edge.\n let zone;\n switch (ad) {\n case al:\n zone = 'widget-left';\n break;\n case at:\n zone = 'widget-top';\n break;\n case ar:\n zone = 'widget-right';\n break;\n case ab:\n zone = 'widget-bottom';\n break;\n default:\n throw 'unreachable';\n }\n // Return the final drop target.\n return { zone, target };\n }\n Private.findDropTarget = findDropTarget;\n /**\n * Get the drop reference widget for a tab bar.\n */\n function getDropRef(tabBar) {\n if (tabBar.titles.length === 0) {\n return null;\n }\n if (tabBar.currentTitle) {\n return tabBar.currentTitle.owner;\n }\n return tabBar.titles[tabBar.titles.length - 1].owner;\n }\n Private.getDropRef = getDropRef;\n})(Private$5 || (Private$5 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A class which tracks focus among a set of widgets.\n *\n * This class is useful when code needs to keep track of the most\n * recently focused widget(s) among a set of related widgets.\n */\nclass FocusTracker {\n constructor() {\n this._counter = 0;\n this._widgets = [];\n this._activeWidget = null;\n this._currentWidget = null;\n this._numbers = new Map();\n this._nodes = new Map();\n this._activeChanged = new Signal(this);\n this._currentChanged = new Signal(this);\n }\n /**\n * Dispose of the resources held by the tracker.\n */\n dispose() {\n // Do nothing if the tracker is already disposed.\n if (this._counter < 0) {\n return;\n }\n // Mark the tracker as disposed.\n this._counter = -1;\n // Clear the connections for the tracker.\n Signal.clearData(this);\n // Remove all event listeners.\n for (const widget of this._widgets) {\n widget.node.removeEventListener('focus', this, true);\n widget.node.removeEventListener('blur', this, true);\n }\n // Clear the internal data structures.\n this._activeWidget = null;\n this._currentWidget = null;\n this._nodes.clear();\n this._numbers.clear();\n this._widgets.length = 0;\n }\n /**\n * A signal emitted when the current widget has changed.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * A signal emitted when the active widget has changed.\n */\n get activeChanged() {\n return this._activeChanged;\n }\n /**\n * A flag indicating whether the tracker is disposed.\n */\n get isDisposed() {\n return this._counter < 0;\n }\n /**\n * The current widget in the tracker.\n *\n * #### Notes\n * The current widget is the widget among the tracked widgets which\n * has the *descendant node* which has most recently been focused.\n *\n * The current widget will not be updated if the node loses focus. It\n * will only be updated when a different tracked widget gains focus.\n *\n * If the current widget is removed from the tracker, the previous\n * current widget will be restored.\n *\n * This behavior is intended to follow a user's conceptual model of\n * a semantically \"current\" widget, where the \"last thing of type X\"\n * to be interacted with is the \"current instance of X\", regardless\n * of whether that instance still has focus.\n */\n get currentWidget() {\n return this._currentWidget;\n }\n /**\n * The active widget in the tracker.\n *\n * #### Notes\n * The active widget is the widget among the tracked widgets which\n * has the *descendant node* which is currently focused.\n */\n get activeWidget() {\n return this._activeWidget;\n }\n /**\n * A read only array of the widgets being tracked.\n */\n get widgets() {\n return this._widgets;\n }\n /**\n * Get the focus number for a particular widget in the tracker.\n *\n * @param widget - The widget of interest.\n *\n * @returns The focus number for the given widget, or `-1` if the\n * widget has not had focus since being added to the tracker, or\n * is not contained by the tracker.\n *\n * #### Notes\n * The focus number indicates the relative order in which the widgets\n * have gained focus. A widget with a larger number has gained focus\n * more recently than a widget with a smaller number.\n *\n * The `currentWidget` will always have the largest focus number.\n *\n * All widgets start with a focus number of `-1`, which indicates that\n * the widget has not been focused since being added to the tracker.\n */\n focusNumber(widget) {\n let n = this._numbers.get(widget);\n return n === undefined ? -1 : n;\n }\n /**\n * Test whether the focus tracker contains a given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns `true` if the widget is tracked, `false` otherwise.\n */\n has(widget) {\n return this._numbers.has(widget);\n }\n /**\n * Add a widget to the focus tracker.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * A widget will be automatically removed from the tracker if it\n * is disposed after being added.\n *\n * If the widget is already tracked, this is a no-op.\n */\n add(widget) {\n // Do nothing if the widget is already tracked.\n if (this._numbers.has(widget)) {\n return;\n }\n // Test whether the widget has focus.\n let focused = widget.node.contains(document.activeElement);\n // Set up the initial focus number.\n let n = focused ? this._counter++ : -1;\n // Add the widget to the internal data structures.\n this._widgets.push(widget);\n this._numbers.set(widget, n);\n this._nodes.set(widget.node, widget);\n // Set up the event listeners. The capturing phase must be used\n // since the 'focus' and 'blur' events don't bubble and Firefox\n // doesn't support the 'focusin' or 'focusout' events.\n widget.node.addEventListener('focus', this, true);\n widget.node.addEventListener('blur', this, true);\n // Connect the disposed signal handler.\n widget.disposed.connect(this._onWidgetDisposed, this);\n // Set the current and active widgets if needed.\n if (focused) {\n this._setWidgets(widget, widget);\n }\n }\n /**\n * Remove a widget from the focus tracker.\n *\n * #### Notes\n * If the widget is the `currentWidget`, the previous current widget\n * will become the new `currentWidget`.\n *\n * A widget will be automatically removed from the tracker if it\n * is disposed after being added.\n *\n * If the widget is not tracked, this is a no-op.\n */\n remove(widget) {\n // Bail early if the widget is not tracked.\n if (!this._numbers.has(widget)) {\n return;\n }\n // Disconnect the disposed signal handler.\n widget.disposed.disconnect(this._onWidgetDisposed, this);\n // Remove the event listeners.\n widget.node.removeEventListener('focus', this, true);\n widget.node.removeEventListener('blur', this, true);\n // Remove the widget from the internal data structures.\n ArrayExt.removeFirstOf(this._widgets, widget);\n this._nodes.delete(widget.node);\n this._numbers.delete(widget);\n // Bail early if the widget is not the current widget.\n if (this._currentWidget !== widget) {\n return;\n }\n // Filter the widgets for those which have had focus.\n let valid = this._widgets.filter(w => this._numbers.get(w) !== -1);\n // Get the valid widget with the max focus number.\n let previous = max(valid, (first, second) => {\n let a = this._numbers.get(first);\n let b = this._numbers.get(second);\n return a - b;\n }) || null;\n // Set the current and active widgets.\n this._setWidgets(previous, null);\n }\n /**\n * Handle the DOM events for the focus tracker.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the tracked nodes. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'focus':\n this._evtFocus(event);\n break;\n case 'blur':\n this._evtBlur(event);\n break;\n }\n }\n /**\n * Set the current and active widgets for the tracker.\n */\n _setWidgets(current, active) {\n // Swap the current widget.\n let oldCurrent = this._currentWidget;\n this._currentWidget = current;\n // Swap the active widget.\n let oldActive = this._activeWidget;\n this._activeWidget = active;\n // Emit the `currentChanged` signal if needed.\n if (oldCurrent !== current) {\n this._currentChanged.emit({ oldValue: oldCurrent, newValue: current });\n }\n // Emit the `activeChanged` signal if needed.\n if (oldActive !== active) {\n this._activeChanged.emit({ oldValue: oldActive, newValue: active });\n }\n }\n /**\n * Handle the `'focus'` event for a tracked widget.\n */\n _evtFocus(event) {\n // Find the widget which gained focus, which is known to exist.\n let widget = this._nodes.get(event.currentTarget);\n // Update the focus number if necessary.\n if (widget !== this._currentWidget) {\n this._numbers.set(widget, this._counter++);\n }\n // Set the current and active widgets.\n this._setWidgets(widget, widget);\n }\n /**\n * Handle the `'blur'` event for a tracked widget.\n */\n _evtBlur(event) {\n // Find the widget which lost focus, which is known to exist.\n let widget = this._nodes.get(event.currentTarget);\n // Get the node which being focused after this blur.\n let focusTarget = event.relatedTarget;\n // If no other node is being focused, clear the active widget.\n if (!focusTarget) {\n this._setWidgets(this._currentWidget, null);\n return;\n }\n // Bail if the focus widget is not changing.\n if (widget.node.contains(focusTarget)) {\n return;\n }\n // If no tracked widget is being focused, clear the active widget.\n if (!find(this._widgets, w => w.node.contains(focusTarget))) {\n this._setWidgets(this._currentWidget, null);\n return;\n }\n }\n /**\n * Handle the `disposed` signal for a tracked widget.\n */\n _onWidgetDisposed(sender) {\n this.remove(sender);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which arranges its widgets in a grid.\n */\nclass GridLayout extends Layout {\n /**\n * Construct a new grid layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options = {}) {\n super(options);\n this._dirty = false;\n this._rowSpacing = 4;\n this._columnSpacing = 4;\n this._items = [];\n this._rowStarts = [];\n this._columnStarts = [];\n this._rowSizers = [new BoxSizer()];\n this._columnSizers = [new BoxSizer()];\n this._box = null;\n if (options.rowCount !== undefined) {\n Private$4.reallocSizers(this._rowSizers, options.rowCount);\n }\n if (options.columnCount !== undefined) {\n Private$4.reallocSizers(this._columnSizers, options.columnCount);\n }\n if (options.rowSpacing !== undefined) {\n this._rowSpacing = Private$4.clampValue(options.rowSpacing);\n }\n if (options.columnSpacing !== undefined) {\n this._columnSpacing = Private$4.clampValue(options.columnSpacing);\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the widgets and layout items.\n for (const item of this._items) {\n let widget = item.widget;\n item.dispose();\n widget.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n this._rowStarts.length = 0;\n this._rowSizers.length = 0;\n this._columnStarts.length = 0;\n this._columnSizers.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Get the number of rows in the layout.\n */\n get rowCount() {\n return this._rowSizers.length;\n }\n /**\n * Set the number of rows in the layout.\n *\n * #### Notes\n * The minimum row count is `1`.\n */\n set rowCount(value) {\n // Do nothing if the row count does not change.\n if (value === this.rowCount) {\n return;\n }\n // Reallocate the row sizers.\n Private$4.reallocSizers(this._rowSizers, value);\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the number of columns in the layout.\n */\n get columnCount() {\n return this._columnSizers.length;\n }\n /**\n * Set the number of columns in the layout.\n *\n * #### Notes\n * The minimum column count is `1`.\n */\n set columnCount(value) {\n // Do nothing if the column count does not change.\n if (value === this.columnCount) {\n return;\n }\n // Reallocate the column sizers.\n Private$4.reallocSizers(this._columnSizers, value);\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the row spacing for the layout.\n */\n get rowSpacing() {\n return this._rowSpacing;\n }\n /**\n * Set the row spacing for the layout.\n */\n set rowSpacing(value) {\n // Clamp the spacing to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the spacing does not change\n if (this._rowSpacing === value) {\n return;\n }\n // Update the internal spacing.\n this._rowSpacing = value;\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the column spacing for the layout.\n */\n get columnSpacing() {\n return this._columnSpacing;\n }\n /**\n * Set the col spacing for the layout.\n */\n set columnSpacing(value) {\n // Clamp the spacing to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the spacing does not change\n if (this._columnSpacing === value) {\n return;\n }\n // Update the internal spacing.\n this._columnSpacing = value;\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the stretch factor for a specific row.\n *\n * @param index - The row index of interest.\n *\n * @returns The stretch factor for the row.\n *\n * #### Notes\n * This returns `-1` if the index is out of range.\n */\n rowStretch(index) {\n let sizer = this._rowSizers[index];\n return sizer ? sizer.stretch : -1;\n }\n /**\n * Set the stretch factor for a specific row.\n *\n * @param index - The row index of interest.\n *\n * @param value - The stretch factor for the row.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n setRowStretch(index, value) {\n // Look up the row sizer.\n let sizer = this._rowSizers[index];\n // Bail if the index is out of range.\n if (!sizer) {\n return;\n }\n // Clamp the value to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the stretch does not change.\n if (sizer.stretch === value) {\n return;\n }\n // Update the sizer stretch.\n sizer.stretch = value;\n // Schedule an update of the parent.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Get the stretch factor for a specific column.\n *\n * @param index - The column index of interest.\n *\n * @returns The stretch factor for the column.\n *\n * #### Notes\n * This returns `-1` if the index is out of range.\n */\n columnStretch(index) {\n let sizer = this._columnSizers[index];\n return sizer ? sizer.stretch : -1;\n }\n /**\n * Set the stretch factor for a specific column.\n *\n * @param index - The column index of interest.\n *\n * @param value - The stretch factor for the column.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n setColumnStretch(index, value) {\n // Look up the column sizer.\n let sizer = this._columnSizers[index];\n // Bail if the index is out of range.\n if (!sizer) {\n return;\n }\n // Clamp the value to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the stretch does not change.\n if (sizer.stretch === value) {\n return;\n }\n // Update the sizer stretch.\n sizer.stretch = value;\n // Schedule an update of the parent.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Create an iterator over the widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n */\n *[Symbol.iterator]() {\n for (const item of this._items) {\n yield item.widget;\n }\n }\n /**\n * Add a widget to the grid layout.\n *\n * @param widget - The widget to add to the layout.\n *\n * #### Notes\n * If the widget is already contained in the layout, this is no-op.\n */\n addWidget(widget) {\n // Look up the index for the widget.\n let i = ArrayExt.findFirstIndex(this._items, it => it.widget === widget);\n // Bail if the widget is already in the layout.\n if (i !== -1) {\n return;\n }\n // Add the widget to the layout.\n this._items.push(new LayoutItem(widget));\n // Attach the widget to the parent.\n if (this.parent) {\n this.attachWidget(widget);\n }\n }\n /**\n * Remove a widget from the grid layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n // Look up the index for the widget.\n let i = ArrayExt.findFirstIndex(this._items, it => it.widget === widget);\n // Bail if the widget is not in the layout.\n if (i === -1) {\n return;\n }\n // Remove the widget from the layout.\n let item = ArrayExt.removeAt(this._items, i);\n // Detach the widget from the parent.\n if (this.parent) {\n this.detachWidget(widget);\n }\n // Dispose the layout item.\n item.dispose();\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n super.init();\n for (const widget of this) {\n this.attachWidget(widget);\n }\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param widget - The widget to attach to the parent.\n */\n attachWidget(widget) {\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param widget - The widget to detach from the parent.\n */\n detachWidget(widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Reset the min sizes of the sizers.\n for (let i = 0, n = this.rowCount; i < n; ++i) {\n this._rowSizers[i].minSize = 0;\n }\n for (let i = 0, n = this.columnCount; i < n; ++i) {\n this._columnSizers[i].minSize = 0;\n }\n // Filter for the visible layout items.\n let items = this._items.filter(it => !it.isHidden);\n // Fit the layout items.\n for (let i = 0, n = items.length; i < n; ++i) {\n items[i].fit();\n }\n // Get the max row and column index.\n let maxRow = this.rowCount - 1;\n let maxCol = this.columnCount - 1;\n // Sort the items by row span.\n items.sort(Private$4.rowSpanCmp);\n // Update the min sizes of the row sizers.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Fetch the item.\n let item = items[i];\n // Get the row bounds for the item.\n let config = GridLayout.getCellConfig(item.widget);\n let r1 = Math.min(config.row, maxRow);\n let r2 = Math.min(config.row + config.rowSpan - 1, maxRow);\n // Distribute the minimum height to the sizers as needed.\n Private$4.distributeMin(this._rowSizers, r1, r2, item.minHeight);\n }\n // Sort the items by column span.\n items.sort(Private$4.columnSpanCmp);\n // Update the min sizes of the column sizers.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Fetch the item.\n let item = items[i];\n // Get the column bounds for the item.\n let config = GridLayout.getCellConfig(item.widget);\n let c1 = Math.min(config.column, maxCol);\n let c2 = Math.min(config.column + config.columnSpan - 1, maxCol);\n // Distribute the minimum width to the sizers as needed.\n Private$4.distributeMin(this._columnSizers, c1, c2, item.minWidth);\n }\n // If no size constraint is needed, just update the parent.\n if (this.fitPolicy === 'set-no-constraint') {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n return;\n }\n // Set up the computed min size.\n let minH = maxRow * this._rowSpacing;\n let minW = maxCol * this._columnSpacing;\n // Add the sizer minimums to the computed min size.\n for (let i = 0, n = this.rowCount; i < n; ++i) {\n minH += this._rowSizers[i].minSize;\n }\n for (let i = 0, n = this.columnCount; i < n; ++i) {\n minW += this._columnSizers[i].minSize;\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the layout area adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Get the max row and column index.\n let maxRow = this.rowCount - 1;\n let maxCol = this.columnCount - 1;\n // Compute the total fixed row and column space.\n let fixedRowSpace = maxRow * this._rowSpacing;\n let fixedColSpace = maxCol * this._columnSpacing;\n // Distribute the available space to the box sizers.\n BoxEngine.calc(this._rowSizers, Math.max(0, height - fixedRowSpace));\n BoxEngine.calc(this._columnSizers, Math.max(0, width - fixedColSpace));\n // Update the row start positions.\n for (let i = 0, pos = top, n = this.rowCount; i < n; ++i) {\n this._rowStarts[i] = pos;\n pos += this._rowSizers[i].size + this._rowSpacing;\n }\n // Update the column start positions.\n for (let i = 0, pos = left, n = this.columnCount; i < n; ++i) {\n this._columnStarts[i] = pos;\n pos += this._columnSizers[i].size + this._columnSpacing;\n }\n // Update the geometry of the layout items.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Fetch the cell bounds for the widget.\n let config = GridLayout.getCellConfig(item.widget);\n let r1 = Math.min(config.row, maxRow);\n let c1 = Math.min(config.column, maxCol);\n let r2 = Math.min(config.row + config.rowSpan - 1, maxRow);\n let c2 = Math.min(config.column + config.columnSpan - 1, maxCol);\n // Compute the cell geometry.\n let x = this._columnStarts[c1];\n let y = this._rowStarts[r1];\n let w = this._columnStarts[c2] + this._columnSizers[c2].size - x;\n let h = this._rowStarts[r2] + this._rowSizers[r2].size - y;\n // Update the geometry of the layout item.\n item.update(x, y, w, h);\n }\n }\n}\n/**\n * The namespace for the `GridLayout` class statics.\n */\n(function (GridLayout) {\n /**\n * Get the cell config for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The cell config for the widget.\n */\n function getCellConfig(widget) {\n return Private$4.cellConfigProperty.get(widget);\n }\n GridLayout.getCellConfig = getCellConfig;\n /**\n * Set the cell config for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the cell config.\n */\n function setCellConfig(widget, value) {\n Private$4.cellConfigProperty.set(widget, Private$4.normalizeConfig(value));\n }\n GridLayout.setCellConfig = setCellConfig;\n})(GridLayout || (GridLayout = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$4;\n(function (Private) {\n /**\n * The property descriptor for the widget cell config.\n */\n Private.cellConfigProperty = new AttachedProperty({\n name: 'cellConfig',\n create: () => ({ row: 0, column: 0, rowSpan: 1, columnSpan: 1 }),\n changed: onChildCellConfigChanged\n });\n /**\n * Normalize a partial cell config object.\n */\n function normalizeConfig(config) {\n let row = Math.max(0, Math.floor(config.row || 0));\n let column = Math.max(0, Math.floor(config.column || 0));\n let rowSpan = Math.max(1, Math.floor(config.rowSpan || 0));\n let columnSpan = Math.max(1, Math.floor(config.columnSpan || 0));\n return { row, column, rowSpan, columnSpan };\n }\n Private.normalizeConfig = normalizeConfig;\n /**\n * Clamp a value to an integer >= 0.\n */\n function clampValue(value) {\n return Math.max(0, Math.floor(value));\n }\n Private.clampValue = clampValue;\n /**\n * A sort comparison function for row spans.\n */\n function rowSpanCmp(a, b) {\n let c1 = Private.cellConfigProperty.get(a.widget);\n let c2 = Private.cellConfigProperty.get(b.widget);\n return c1.rowSpan - c2.rowSpan;\n }\n Private.rowSpanCmp = rowSpanCmp;\n /**\n * A sort comparison function for column spans.\n */\n function columnSpanCmp(a, b) {\n let c1 = Private.cellConfigProperty.get(a.widget);\n let c2 = Private.cellConfigProperty.get(b.widget);\n return c1.columnSpan - c2.columnSpan;\n }\n Private.columnSpanCmp = columnSpanCmp;\n /**\n * Reallocate the box sizers for the given grid dimensions.\n */\n function reallocSizers(sizers, count) {\n // Coerce the count to the valid range.\n count = Math.max(1, Math.floor(count));\n // Add the missing sizers.\n while (sizers.length < count) {\n sizers.push(new BoxSizer());\n }\n // Remove the extra sizers.\n if (sizers.length > count) {\n sizers.length = count;\n }\n }\n Private.reallocSizers = reallocSizers;\n /**\n * Distribute a min size constraint across a range of sizers.\n */\n function distributeMin(sizers, i1, i2, minSize) {\n // Sanity check the indices.\n if (i2 < i1) {\n return;\n }\n // Handle the simple case of no cell span.\n if (i1 === i2) {\n let sizer = sizers[i1];\n sizer.minSize = Math.max(sizer.minSize, minSize);\n return;\n }\n // Compute the total current min size of the span.\n let totalMin = 0;\n for (let i = i1; i <= i2; ++i) {\n totalMin += sizers[i].minSize;\n }\n // Do nothing if the total is greater than the required.\n if (totalMin >= minSize) {\n return;\n }\n // Compute the portion of the space to allocate to each sizer.\n let portion = (minSize - totalMin) / (i2 - i1 + 1);\n // Add the portion to each sizer.\n for (let i = i1; i <= i2; ++i) {\n sizers[i].minSize += portion;\n }\n }\n Private.distributeMin = distributeMin;\n /**\n * The change handler for the child cell config property.\n */\n function onChildCellConfigChanged(child) {\n if (child.parent && child.parent.layout instanceof GridLayout) {\n child.parent.fit();\n }\n }\n})(Private$4 || (Private$4 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which displays menus as a canonical menu bar.\n */\nclass MenuBar extends Widget {\n /**\n * Construct a new menu bar.\n *\n * @param options - The options for initializing the menu bar.\n */\n constructor(options = {}) {\n super({ node: Private$3.createNode() });\n // Track the index of the item that is currently focused or hovered. -1 means nothing focused or hovered.\n this._activeIndex = -1;\n // Track which item can be focused using the TAB key. Unlike _activeIndex will\n // always point to a menuitem. Whenever you update this value, it's important\n // to follow it with an \"update-request\" message so that the `tabindex`\n // attribute on each menubar item gets properly updated.\n this._tabFocusIndex = 0;\n this._menus = [];\n this._childMenu = null;\n this._overflowMenu = null;\n this._menuItemSizes = [];\n this._overflowIndex = -1;\n this.addClass('lm-MenuBar');\n this.setFlag(Widget.Flag.DisallowLayout);\n this.renderer = options.renderer || MenuBar.defaultRenderer;\n this._forceItemsPosition = options.forceItemsPosition || {\n forceX: true,\n forceY: true\n };\n this._overflowMenuOptions = options.overflowMenuOptions || {\n isVisible: true\n };\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n this._closeChildMenu();\n this._menus.length = 0;\n super.dispose();\n }\n /**\n * The child menu of the menu bar.\n *\n * #### Notes\n * This will be `null` if the menu bar does not have an open menu.\n */\n get childMenu() {\n return this._childMenu;\n }\n /**\n * The overflow index of the menu bar.\n */\n get overflowIndex() {\n return this._overflowIndex;\n }\n /**\n * The overflow menu of the menu bar.\n */\n get overflowMenu() {\n return this._overflowMenu;\n }\n /**\n * Get the menu bar content node.\n *\n * #### Notes\n * This is the node which holds the menu title nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-MenuBar-content')[0];\n }\n /**\n * Get the currently active menu.\n */\n get activeMenu() {\n return this._menus[this._activeIndex] || null;\n }\n /**\n * Set the currently active menu.\n *\n * #### Notes\n * If the menu does not exist, the menu will be set to `null`.\n */\n set activeMenu(value) {\n this.activeIndex = value ? this._menus.indexOf(value) : -1;\n }\n /**\n * Get the index of the currently active menu.\n *\n * #### Notes\n * This will be `-1` if no menu is active.\n */\n get activeIndex() {\n return this._activeIndex;\n }\n /**\n * Set the index of the currently active menu.\n *\n * #### Notes\n * If the menu cannot be activated, the index will be set to `-1`.\n */\n set activeIndex(value) {\n // Adjust the value for an out of range index.\n if (value < 0 || value >= this._menus.length) {\n value = -1;\n }\n // An empty menu cannot be active\n if (value > -1 && this._menus[value].items.length === 0) {\n value = -1;\n }\n // Bail early if the index will not change.\n if (this._activeIndex === value) {\n return;\n }\n // Update the active index.\n this._activeIndex = value;\n // Schedule an update of the items.\n this.update();\n }\n /**\n * A read-only array of the menus in the menu bar.\n */\n get menus() {\n return this._menus;\n }\n /**\n * Open the active menu and activate its first menu item.\n *\n * #### Notes\n * If there is no active menu, this is a no-op.\n */\n openActiveMenu() {\n // Bail early if there is no active item.\n if (this._activeIndex === -1) {\n return;\n }\n // Open the child menu.\n this._openChildMenu();\n // Activate the first item in the child menu.\n if (this._childMenu) {\n this._childMenu.activeIndex = -1;\n this._childMenu.activateNextItem();\n }\n }\n /**\n * Add a menu to the end of the menu bar.\n *\n * @param menu - The menu to add to the menu bar.\n *\n * #### Notes\n * If the menu is already added to the menu bar, it will be moved.\n */\n addMenu(menu, update = true) {\n this.insertMenu(this._menus.length, menu, update);\n }\n /**\n * Insert a menu into the menu bar at the specified index.\n *\n * @param index - The index at which to insert the menu.\n *\n * @param menu - The menu to insert into the menu bar.\n *\n * #### Notes\n * The index will be clamped to the bounds of the menus.\n *\n * If the menu is already added to the menu bar, it will be moved.\n */\n insertMenu(index, menu, update = true) {\n // Close the child menu before making changes.\n this._closeChildMenu();\n // Look up the index of the menu.\n let i = this._menus.indexOf(menu);\n // Clamp the insert index to the array bounds.\n let j = Math.max(0, Math.min(index, this._menus.length));\n // If the menu is not in the array, insert it.\n if (i === -1) {\n // Insert the menu into the array.\n ArrayExt.insert(this._menus, j, menu);\n // Add the styling class to the menu.\n menu.addClass('lm-MenuBar-menu');\n // Connect to the menu signals.\n menu.aboutToClose.connect(this._onMenuAboutToClose, this);\n menu.menuRequested.connect(this._onMenuMenuRequested, this);\n menu.title.changed.connect(this._onTitleChanged, this);\n // Schedule an update of the items.\n if (update) {\n this.update();\n }\n // There is nothing more to do.\n return;\n }\n // Otherwise, the menu exists in the array and should be moved.\n // Adjust the index if the location is at the end of the array.\n if (j === this._menus.length) {\n j--;\n }\n // Bail if there is no effective move.\n if (i === j) {\n return;\n }\n // Move the menu to the new locations.\n ArrayExt.move(this._menus, i, j);\n // Schedule an update of the items.\n if (update) {\n this.update();\n }\n }\n /**\n * Remove a menu from the menu bar.\n *\n * @param menu - The menu to remove from the menu bar.\n *\n * #### Notes\n * This is a no-op if the menu is not in the menu bar.\n */\n removeMenu(menu, update = true) {\n this.removeMenuAt(this._menus.indexOf(menu), update);\n }\n /**\n * Remove the menu at a given index from the menu bar.\n *\n * @param index - The index of the menu to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeMenuAt(index, update = true) {\n // Close the child menu before making changes.\n this._closeChildMenu();\n // Remove the menu from the array.\n let menu = ArrayExt.removeAt(this._menus, index);\n // Bail if the index is out of range.\n if (!menu) {\n return;\n }\n // Disconnect from the menu signals.\n menu.aboutToClose.disconnect(this._onMenuAboutToClose, this);\n menu.menuRequested.disconnect(this._onMenuMenuRequested, this);\n menu.title.changed.disconnect(this._onTitleChanged, this);\n // Remove the styling class from the menu.\n menu.removeClass('lm-MenuBar-menu');\n // Schedule an update of the items.\n if (update) {\n this.update();\n }\n }\n /**\n * Remove all menus from the menu bar.\n */\n clearMenus() {\n // Bail if there is nothing to remove.\n if (this._menus.length === 0) {\n return;\n }\n // Close the child menu before making changes.\n this._closeChildMenu();\n // Disconnect from the menu signals and remove the styling class.\n for (let menu of this._menus) {\n menu.aboutToClose.disconnect(this._onMenuAboutToClose, this);\n menu.menuRequested.disconnect(this._onMenuMenuRequested, this);\n menu.title.changed.disconnect(this._onTitleChanged, this);\n menu.removeClass('lm-MenuBar-menu');\n }\n // Clear the menus array.\n this._menus.length = 0;\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Handle the DOM events for the menu bar.\n *\n * @param event - The DOM event sent to the menu bar.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the menu bar's DOM nodes. It\n * should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'mousedown':\n this._evtMouseDown(event);\n break;\n case 'mousemove':\n this._evtMouseMove(event);\n break;\n case 'focusout':\n this._evtFocusOut(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('keydown', this);\n this.node.addEventListener('mousedown', this);\n this.node.addEventListener('mousemove', this);\n this.node.addEventListener('focusout', this);\n this.node.addEventListener('contextmenu', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('keydown', this);\n this.node.removeEventListener('mousedown', this);\n this.node.removeEventListener('mousemove', this);\n this.node.removeEventListener('focusout', this);\n this.node.removeEventListener('contextmenu', this);\n this._closeChildMenu();\n }\n /**\n * A message handler invoked on an `'activate-request'` message.\n */\n onActivateRequest(msg) {\n if (this.isAttached) {\n this._focusItemAt(0);\n }\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n this.update();\n super.onResize(msg);\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n var _a;\n let menus = this._menus;\n let renderer = this.renderer;\n let activeIndex = this._activeIndex;\n let tabFocusIndex = this._tabFocusIndex >= 0 && this._tabFocusIndex < menus.length\n ? this._tabFocusIndex\n : 0;\n let length = this._overflowIndex > -1 ? this._overflowIndex : menus.length;\n let totalMenuSize = 0;\n let isVisible = false;\n // Check that the overflow menu doesn't count\n length = this._overflowMenu !== null ? length - 1 : length;\n let content = new Array(length);\n // Render visible menus\n for (let i = 0; i < length; ++i) {\n content[i] = renderer.renderItem({\n title: menus[i].title,\n active: i === activeIndex,\n tabbable: i === tabFocusIndex,\n disabled: menus[i].items.length === 0,\n onfocus: () => {\n this._tabFocusIndex = i;\n this.activeIndex = i;\n }\n });\n // Calculate size of current menu\n totalMenuSize += this._menuItemSizes[i];\n // Check if overflow menu is already rendered\n if (menus[i].title.label === this._overflowMenuOptions.title) {\n isVisible = true;\n length--;\n }\n }\n // Render overflow menu if needed and active\n if (this._overflowMenuOptions.isVisible) {\n if (this._overflowIndex > -1 && !isVisible) {\n // Create overflow menu\n if (this._overflowMenu === null) {\n const overflowMenuTitle = (_a = this._overflowMenuOptions.title) !== null && _a !== void 0 ? _a : '...';\n this._overflowMenu = new Menu({ commands: new CommandRegistry() });\n this._overflowMenu.title.label = overflowMenuTitle;\n this._overflowMenu.title.mnemonic = 0;\n this.addMenu(this._overflowMenu, false);\n }\n // Move menus to overflow menu\n for (let i = menus.length - 2; i >= length; i--) {\n const submenu = this.menus[i];\n submenu.title.mnemonic = 0;\n this._overflowMenu.insertItem(0, {\n type: 'submenu',\n submenu: submenu\n });\n this.removeMenu(submenu, false);\n }\n content[length] = renderer.renderItem({\n title: this._overflowMenu.title,\n active: length === activeIndex && menus[length].items.length !== 0,\n tabbable: length === tabFocusIndex,\n disabled: menus[length].items.length === 0,\n onfocus: () => {\n this._tabFocusIndex = length;\n this.activeIndex = length;\n }\n });\n length++;\n }\n else if (this._overflowMenu !== null) {\n // Remove submenus from overflow menu\n let overflowMenuItems = this._overflowMenu.items;\n let screenSize = this.node.offsetWidth;\n let n = this._overflowMenu.items.length;\n for (let i = 0; i < n; ++i) {\n let index = menus.length - 1 - i;\n if (screenSize - totalMenuSize > this._menuItemSizes[index]) {\n let menu = overflowMenuItems[0].submenu;\n this._overflowMenu.removeItemAt(0);\n this.insertMenu(length, menu, false);\n content[length] = renderer.renderItem({\n title: menu.title,\n active: false,\n tabbable: length === tabFocusIndex,\n disabled: menus[length].items.length === 0,\n onfocus: () => {\n this._tabFocusIndex = length;\n this.activeIndex = length;\n }\n });\n length++;\n }\n }\n if (this._overflowMenu.items.length === 0) {\n this.removeMenu(this._overflowMenu, false);\n content.pop();\n this._overflowMenu = null;\n this._overflowIndex = -1;\n }\n }\n }\n VirtualDOM.render(content, this.contentNode);\n this._updateOverflowIndex();\n }\n /**\n * Calculate and update the current overflow index.\n */\n _updateOverflowIndex() {\n if (!this._overflowMenuOptions.isVisible) {\n return;\n }\n // Get elements visible in the main menu bar\n const itemMenus = this.contentNode.childNodes;\n let screenSize = this.node.offsetWidth;\n let totalMenuSize = 0;\n let index = -1;\n let n = itemMenus.length;\n if (this._menuItemSizes.length == 0) {\n // Check if it is the first resize and get info about menu items sizes\n for (let i = 0; i < n; i++) {\n let item = itemMenus[i];\n // Add sizes to array\n totalMenuSize += item.offsetWidth;\n this._menuItemSizes.push(item.offsetWidth);\n if (totalMenuSize > screenSize && index === -1) {\n index = i;\n }\n }\n }\n else {\n // Calculate current menu size\n for (let i = 0; i < this._menuItemSizes.length; i++) {\n totalMenuSize += this._menuItemSizes[i];\n if (totalMenuSize > screenSize) {\n index = i;\n break;\n }\n }\n }\n this._overflowIndex = index;\n }\n /**\n * Handle the `'keydown'` event for the menu bar.\n *\n * #### Notes\n * All keys are trapped except the tab key that is ignored.\n */\n _evtKeyDown(event) {\n // Fetch the key code for the event.\n let kc = event.keyCode;\n // Reset the active index on tab, but do not trap the tab key.\n if (kc === 9) {\n this.activeIndex = -1;\n return;\n }\n // A menu bar handles all other keydown events.\n event.preventDefault();\n event.stopPropagation();\n // Enter, Space, Up Arrow, Down Arrow\n if (kc === 13 || kc === 32 || kc === 38 || kc === 40) {\n // The active index may have changed (for example, user hovers over an\n // item with the mouse), so be sure to use the focus index.\n this.activeIndex = this._tabFocusIndex;\n if (this.activeIndex !== this._tabFocusIndex) {\n // Bail if the setter refused to set activeIndex to tabFocusIndex\n // because it means that the item at tabFocusIndex cannot be opened (for\n // example, it has an empty menu)\n return;\n }\n this.openActiveMenu();\n return;\n }\n // Escape\n if (kc === 27) {\n this._closeChildMenu();\n this._focusItemAt(this.activeIndex);\n return;\n }\n // Left or Right Arrow\n if (kc === 37 || kc === 39) {\n let direction = kc === 37 ? -1 : 1;\n let start = this._tabFocusIndex + direction;\n let n = this._menus.length;\n for (let i = 0; i < n; i++) {\n let index = (n + start + direction * i) % n;\n if (this._menus[index].items.length) {\n this._focusItemAt(index);\n return;\n }\n }\n return;\n }\n // Get the pressed key character.\n let key = getKeyboardLayout().keyForKeydownEvent(event);\n // Bail if the key is not valid.\n if (!key) {\n return;\n }\n // Search for the next best matching mnemonic item.\n let start = this._activeIndex + 1;\n let result = Private$3.findMnemonic(this._menus, key, start);\n // Handle the requested mnemonic based on the search results.\n // If exactly one mnemonic is matched, that menu is opened.\n // Otherwise, the next mnemonic is activated if available,\n // followed by the auto mnemonic if available.\n if (result.index !== -1 && !result.multiple) {\n this.activeIndex = result.index;\n this.openActiveMenu();\n }\n else if (result.index !== -1) {\n this.activeIndex = result.index;\n this._focusItemAt(this.activeIndex);\n }\n else if (result.auto !== -1) {\n this.activeIndex = result.auto;\n this._focusItemAt(this.activeIndex);\n }\n }\n /**\n * Handle the `'mousedown'` event for the menu bar.\n */\n _evtMouseDown(event) {\n // Bail if the mouse press was not on the menu bar. This can occur\n // when the document listener is installed for an active menu bar.\n if (!ElementExt.hitTest(this.node, event.clientX, event.clientY)) {\n return;\n }\n // Stop the propagation of the event. Immediate propagation is\n // also stopped so that an open menu does not handle the event.\n event.stopPropagation();\n event.stopImmediatePropagation();\n // Check if the mouse is over one of the menu items.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return ElementExt.hitTest(node, event.clientX, event.clientY);\n });\n // If the press was not on an item, close the child menu.\n if (index === -1) {\n this._closeChildMenu();\n return;\n }\n // If the press was not the left mouse button, do nothing further.\n if (event.button !== 0) {\n return;\n }\n // Otherwise, toggle the open state of the child menu.\n if (this._childMenu) {\n this._closeChildMenu();\n this.activeIndex = index;\n }\n else {\n // If we don't call preventDefault() here, then the item in the menu\n // bar will take focus over the menu that is being opened.\n event.preventDefault();\n const position = this._positionForMenu(index);\n Menu.saveWindowData();\n // Begin DOM modifications.\n this.activeIndex = index;\n this._openChildMenu(position);\n }\n }\n /**\n * Handle the `'mousemove'` event for the menu bar.\n */\n _evtMouseMove(event) {\n // Check if the mouse is over one of the menu items.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return ElementExt.hitTest(node, event.clientX, event.clientY);\n });\n // Bail early if the active index will not change.\n if (index === this._activeIndex) {\n return;\n }\n // Bail early if a child menu is open and the mouse is not over\n // an item. This allows the child menu to be kept open when the\n // mouse is over the empty part of the menu bar.\n if (index === -1 && this._childMenu) {\n return;\n }\n // Get position for the new menu >before< updating active index.\n const position = index >= 0 && this._childMenu ? this._positionForMenu(index) : null;\n // Before any modification, update window data.\n Menu.saveWindowData();\n // Begin DOM modifications.\n // Update the active index to the hovered item.\n this.activeIndex = index;\n // Open the new menu if a menu is already open.\n if (position) {\n this._openChildMenu(position);\n }\n }\n /**\n * Find initial position for the menu based on menubar item position.\n *\n * NOTE: this should be called before updating active index to avoid\n * an additional layout and style invalidation as changing active\n * index modifies DOM.\n */\n _positionForMenu(index) {\n let itemNode = this.contentNode.children[index];\n let { left, bottom } = itemNode.getBoundingClientRect();\n return {\n top: bottom,\n left\n };\n }\n /**\n * Handle the `'focusout'` event for the menu bar.\n */\n _evtFocusOut(event) {\n // Reset the active index if there is no open menu and the menubar is losing focus.\n if (!this._childMenu && !this.node.contains(event.relatedTarget)) {\n this.activeIndex = -1;\n }\n }\n /**\n * Focus an item in the menu bar.\n *\n * #### Notes\n * Does not open the associated menu.\n */\n _focusItemAt(index) {\n const itemNode = this.contentNode.childNodes[index];\n if (itemNode) {\n itemNode.focus();\n }\n }\n /**\n * Open the child menu at the active index immediately.\n *\n * If a different child menu is already open, it will be closed,\n * even if there is no active menu.\n */\n _openChildMenu(options = {}) {\n // If there is no active menu, close the current menu.\n let newMenu = this.activeMenu;\n if (!newMenu) {\n this._closeChildMenu();\n return;\n }\n // Bail if there is no effective menu change.\n let oldMenu = this._childMenu;\n if (oldMenu === newMenu) {\n return;\n }\n // Swap the internal menu reference.\n this._childMenu = newMenu;\n // Close the current menu, or setup for the new menu.\n if (oldMenu) {\n oldMenu.close();\n }\n else {\n document.addEventListener('mousedown', this, true);\n }\n // Update the tab focus index and ensure the menu bar is updated.\n this._tabFocusIndex = this.activeIndex;\n MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);\n // Get the positioning data for the new menu.\n let { left, top } = options;\n if (typeof left === 'undefined' || typeof top === 'undefined') {\n ({ left, top } = this._positionForMenu(this._activeIndex));\n }\n // Begin DOM modifications\n if (!oldMenu) {\n // Continue setup for new menu\n this.addClass('lm-mod-active');\n }\n // Open the new menu at the computed location.\n if (newMenu.items.length > 0) {\n newMenu.open(left, top, this._forceItemsPosition);\n }\n }\n /**\n * Close the child menu immediately.\n *\n * This is a no-op if a child menu is not open.\n */\n _closeChildMenu() {\n // Bail if no child menu is open.\n if (!this._childMenu) {\n return;\n }\n // Remove the active class from the menu bar.\n this.removeClass('lm-mod-active');\n // Remove the document listeners.\n document.removeEventListener('mousedown', this, true);\n // Clear the internal menu reference.\n let menu = this._childMenu;\n this._childMenu = null;\n // Close the menu.\n menu.close();\n // Reset the active index.\n this.activeIndex = -1;\n }\n /**\n * Handle the `aboutToClose` signal of a menu.\n */\n _onMenuAboutToClose(sender) {\n // Bail if the sender is not the child menu.\n if (sender !== this._childMenu) {\n return;\n }\n // Remove the active class from the menu bar.\n this.removeClass('lm-mod-active');\n // Remove the document listeners.\n document.removeEventListener('mousedown', this, true);\n // Clear the internal menu reference.\n this._childMenu = null;\n // Reset the active index.\n this.activeIndex = -1;\n }\n /**\n * Handle the `menuRequested` signal of a child menu.\n */\n _onMenuMenuRequested(sender, args) {\n // Bail if the sender is not the child menu.\n if (sender !== this._childMenu) {\n return;\n }\n // Look up the active index and menu count.\n let i = this._activeIndex;\n let n = this._menus.length;\n // Active the next requested index.\n switch (args) {\n case 'next':\n this.activeIndex = i === n - 1 ? 0 : i + 1;\n break;\n case 'previous':\n this.activeIndex = i === 0 ? n - 1 : i - 1;\n break;\n }\n // Open the active menu.\n this.openActiveMenu();\n }\n /**\n * Handle the `changed` signal of a title object.\n */\n _onTitleChanged() {\n this.update();\n }\n}\n/**\n * The namespace for the `MenuBar` class statics.\n */\n(function (MenuBar) {\n /**\n * The default implementation of `IRenderer`.\n *\n * #### Notes\n * Subclasses are free to reimplement rendering methods as needed.\n */\n class Renderer {\n /**\n * Render the virtual element for a menu bar item.\n *\n * @param data - The data to use for rendering the item.\n *\n * @returns A virtual element representing the item.\n */\n renderItem(data) {\n let className = this.createItemClass(data);\n let dataset = this.createItemDataset(data);\n let aria = this.createItemARIA(data);\n return h.li({\n className,\n dataset,\n ...(data.disabled ? {} : { tabindex: data.tabbable ? '0' : '-1' }),\n onfocus: data.onfocus,\n ...aria\n }, this.renderIcon(data), this.renderLabel(data));\n }\n /**\n * Render the icon element for a menu bar item.\n *\n * @param data - The data to use for rendering the icon.\n *\n * @returns A virtual element representing the item icon.\n */\n renderIcon(data) {\n let className = this.createIconClass(data);\n // If data.title.icon is undefined, it will be ignored.\n return h.div({ className }, data.title.icon, data.title.iconLabel);\n }\n /**\n * Render the label element for a menu item.\n *\n * @param data - The data to use for rendering the label.\n *\n * @returns A virtual element representing the item label.\n */\n renderLabel(data) {\n let content = this.formatLabel(data);\n return h.div({ className: 'lm-MenuBar-itemLabel' }, content);\n }\n /**\n * Create the class name for the menu bar item.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the menu item.\n */\n createItemClass(data) {\n let name = 'lm-MenuBar-item';\n if (data.title.className) {\n name += ` ${data.title.className}`;\n }\n if (data.active && !data.disabled) {\n name += ' lm-mod-active';\n }\n return name;\n }\n /**\n * Create the dataset for a menu bar item.\n *\n * @param data - The data to use for the item.\n *\n * @returns The dataset for the menu bar item.\n */\n createItemDataset(data) {\n return data.title.dataset;\n }\n /**\n * Create the aria attributes for menu bar item.\n *\n * @param data - The data to use for the aria attributes.\n *\n * @returns The aria attributes object for the item.\n */\n createItemARIA(data) {\n return {\n role: 'menuitem',\n 'aria-haspopup': 'true',\n 'aria-disabled': data.disabled ? 'true' : 'false'\n };\n }\n /**\n * Create the class name for the menu bar item icon.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the item icon.\n */\n createIconClass(data) {\n let name = 'lm-MenuBar-itemIcon';\n let extra = data.title.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n /**\n * Create the render content for the label node.\n *\n * @param data - The data to use for the label content.\n *\n * @returns The content to add to the label node.\n */\n formatLabel(data) {\n // Fetch the label text and mnemonic index.\n let { label, mnemonic } = data.title;\n // If the index is out of range, do not modify the label.\n if (mnemonic < 0 || mnemonic >= label.length) {\n return label;\n }\n // Split the label into parts.\n let prefix = label.slice(0, mnemonic);\n let suffix = label.slice(mnemonic + 1);\n let char = label[mnemonic];\n // Wrap the mnemonic character in a span.\n let span = h.span({ className: 'lm-MenuBar-itemMnemonic' }, char);\n // Return the content parts.\n return [prefix, span, suffix];\n }\n }\n MenuBar.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n MenuBar.defaultRenderer = new Renderer();\n})(MenuBar || (MenuBar = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$3;\n(function (Private) {\n /**\n * Create the DOM node for a menu bar.\n */\n function createNode() {\n let node = document.createElement('div');\n let content = document.createElement('ul');\n content.className = 'lm-MenuBar-content';\n node.appendChild(content);\n content.setAttribute('role', 'menubar');\n return node;\n }\n Private.createNode = createNode;\n /**\n * Find the best matching mnemonic item.\n *\n * The search starts at the given index and wraps around.\n */\n function findMnemonic(menus, key, start) {\n // Setup the result variables.\n let index = -1;\n let auto = -1;\n let multiple = false;\n // Normalize the key to upper case.\n let upperKey = key.toUpperCase();\n // Search the items from the given start index.\n for (let i = 0, n = menus.length; i < n; ++i) {\n // Compute the wrapped index.\n let k = (i + start) % n;\n // Look up the menu title.\n let title = menus[k].title;\n // Ignore titles with an empty label.\n if (title.label.length === 0) {\n continue;\n }\n // Look up the mnemonic index for the label.\n let mn = title.mnemonic;\n // Handle a valid mnemonic index.\n if (mn >= 0 && mn < title.label.length) {\n if (title.label[mn].toUpperCase() === upperKey) {\n if (index === -1) {\n index = k;\n }\n else {\n multiple = true;\n }\n }\n continue;\n }\n // Finally, handle the auto index if possible.\n if (auto === -1 && title.label[0].toUpperCase() === upperKey) {\n auto = k;\n }\n }\n // Return the search results.\n return { index, multiple, auto };\n }\n Private.findMnemonic = findMnemonic;\n})(Private$3 || (Private$3 = {}));\n\n/**\n * A widget which implements a canonical scroll bar.\n */\nclass ScrollBar extends Widget {\n /**\n * Construct a new scroll bar.\n *\n * @param options - The options for initializing the scroll bar.\n */\n constructor(options = {}) {\n super({ node: Private$2.createNode() });\n /**\n * A timeout callback for repeating the mouse press.\n */\n this._onRepeat = () => {\n // Clear the repeat timer id.\n this._repeatTimer = -1;\n // Bail if the mouse has been released.\n if (!this._pressData) {\n return;\n }\n // Look up the part that was pressed.\n let part = this._pressData.part;\n // Bail if the thumb was pressed.\n if (part === 'thumb') {\n return;\n }\n // Schedule the timer for another repeat.\n this._repeatTimer = window.setTimeout(this._onRepeat, 20);\n // Get the current mouse position.\n let mouseX = this._pressData.mouseX;\n let mouseY = this._pressData.mouseY;\n // Handle a decrement button repeat.\n if (part === 'decrement') {\n // Bail if the mouse is not over the button.\n if (!ElementExt.hitTest(this.decrementNode, mouseX, mouseY)) {\n return;\n }\n // Emit the step requested signal.\n this._stepRequested.emit('decrement');\n // Finished.\n return;\n }\n // Handle an increment button repeat.\n if (part === 'increment') {\n // Bail if the mouse is not over the button.\n if (!ElementExt.hitTest(this.incrementNode, mouseX, mouseY)) {\n return;\n }\n // Emit the step requested signal.\n this._stepRequested.emit('increment');\n // Finished.\n return;\n }\n // Handle a track repeat.\n if (part === 'track') {\n // Bail if the mouse is not over the track.\n if (!ElementExt.hitTest(this.trackNode, mouseX, mouseY)) {\n return;\n }\n // Fetch the thumb node.\n let thumbNode = this.thumbNode;\n // Bail if the mouse is over the thumb.\n if (ElementExt.hitTest(thumbNode, mouseX, mouseY)) {\n return;\n }\n // Fetch the client rect for the thumb.\n let thumbRect = thumbNode.getBoundingClientRect();\n // Determine the direction for the page request.\n let dir;\n if (this._orientation === 'horizontal') {\n dir = mouseX < thumbRect.left ? 'decrement' : 'increment';\n }\n else {\n dir = mouseY < thumbRect.top ? 'decrement' : 'increment';\n }\n // Emit the page requested signal.\n this._pageRequested.emit(dir);\n // Finished.\n return;\n }\n };\n this._value = 0;\n this._page = 10;\n this._maximum = 100;\n this._repeatTimer = -1;\n this._pressData = null;\n this._thumbMoved = new Signal(this);\n this._stepRequested = new Signal(this);\n this._pageRequested = new Signal(this);\n this.addClass('lm-ScrollBar');\n this.setFlag(Widget.Flag.DisallowLayout);\n // Set the orientation.\n this._orientation = options.orientation || 'vertical';\n this.dataset['orientation'] = this._orientation;\n // Parse the rest of the options.\n if (options.maximum !== undefined) {\n this._maximum = Math.max(0, options.maximum);\n }\n if (options.page !== undefined) {\n this._page = Math.max(0, options.page);\n }\n if (options.value !== undefined) {\n this._value = Math.max(0, Math.min(options.value, this._maximum));\n }\n }\n /**\n * A signal emitted when the user moves the scroll thumb.\n *\n * #### Notes\n * The payload is the current value of the scroll bar.\n */\n get thumbMoved() {\n return this._thumbMoved;\n }\n /**\n * A signal emitted when the user clicks a step button.\n *\n * #### Notes\n * The payload is whether a decrease or increase is requested.\n */\n get stepRequested() {\n return this._stepRequested;\n }\n /**\n * A signal emitted when the user clicks the scroll track.\n *\n * #### Notes\n * The payload is whether a decrease or increase is requested.\n */\n get pageRequested() {\n return this._pageRequested;\n }\n /**\n * Get the orientation of the scroll bar.\n */\n get orientation() {\n return this._orientation;\n }\n /**\n * Set the orientation of the scroll bar.\n */\n set orientation(value) {\n // Do nothing if the orientation does not change.\n if (this._orientation === value) {\n return;\n }\n // Release the mouse before making changes.\n this._releaseMouse();\n // Update the internal orientation.\n this._orientation = value;\n this.dataset['orientation'] = value;\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * Get the current value of the scroll bar.\n */\n get value() {\n return this._value;\n }\n /**\n * Set the current value of the scroll bar.\n *\n * #### Notes\n * The value will be clamped to the range `[0, maximum]`.\n */\n set value(value) {\n // Clamp the value to the allowable range.\n value = Math.max(0, Math.min(value, this._maximum));\n // Do nothing if the value does not change.\n if (this._value === value) {\n return;\n }\n // Update the internal value.\n this._value = value;\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * Get the page size of the scroll bar.\n *\n * #### Notes\n * The page size is the amount of visible content in the scrolled\n * region, expressed in data units. It determines the size of the\n * scroll bar thumb.\n */\n get page() {\n return this._page;\n }\n /**\n * Set the page size of the scroll bar.\n *\n * #### Notes\n * The page size will be clamped to the range `[0, Infinity]`.\n */\n set page(value) {\n // Clamp the page size to the allowable range.\n value = Math.max(0, value);\n // Do nothing if the value does not change.\n if (this._page === value) {\n return;\n }\n // Update the internal page size.\n this._page = value;\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * Get the maximum value of the scroll bar.\n */\n get maximum() {\n return this._maximum;\n }\n /**\n * Set the maximum value of the scroll bar.\n *\n * #### Notes\n * The max size will be clamped to the range `[0, Infinity]`.\n */\n set maximum(value) {\n // Clamp the value to the allowable range.\n value = Math.max(0, value);\n // Do nothing if the value does not change.\n if (this._maximum === value) {\n return;\n }\n // Update the internal values.\n this._maximum = value;\n // Clamp the current value to the new range.\n this._value = Math.min(this._value, value);\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * The scroll bar decrement button node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get decrementNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-button')[0];\n }\n /**\n * The scroll bar increment button node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get incrementNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-button')[1];\n }\n /**\n * The scroll bar track node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get trackNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-track')[0];\n }\n /**\n * The scroll bar thumb node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get thumbNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-thumb')[0];\n }\n /**\n * Handle the DOM events for the scroll bar.\n *\n * @param event - The DOM event sent to the scroll bar.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the scroll bar's DOM node.\n *\n * This should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'mousedown':\n this._evtMouseDown(event);\n break;\n case 'mousemove':\n this._evtMouseMove(event);\n break;\n case 'mouseup':\n this._evtMouseUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A method invoked on a 'before-attach' message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('mousedown', this);\n this.update();\n }\n /**\n * A method invoked on an 'after-detach' message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('mousedown', this);\n this._releaseMouse();\n }\n /**\n * A method invoked on an 'update-request' message.\n */\n onUpdateRequest(msg) {\n // Convert the value and page into percentages.\n let value = (this._value * 100) / this._maximum;\n let page = (this._page * 100) / (this._page + this._maximum);\n // Clamp the value and page to the relevant range.\n value = Math.max(0, Math.min(value, 100));\n page = Math.max(0, Math.min(page, 100));\n // Fetch the thumb style.\n let thumbStyle = this.thumbNode.style;\n // Update the thumb style for the current orientation.\n if (this._orientation === 'horizontal') {\n thumbStyle.top = '';\n thumbStyle.height = '';\n thumbStyle.left = `${value}%`;\n thumbStyle.width = `${page}%`;\n thumbStyle.transform = `translate(${-value}%, 0%)`;\n }\n else {\n thumbStyle.left = '';\n thumbStyle.width = '';\n thumbStyle.top = `${value}%`;\n thumbStyle.height = `${page}%`;\n thumbStyle.transform = `translate(0%, ${-value}%)`;\n }\n }\n /**\n * Handle the `'keydown'` event for the scroll bar.\n */\n _evtKeyDown(event) {\n // Stop all input events during drag.\n event.preventDefault();\n event.stopPropagation();\n // Ignore anything except the `Escape` key.\n if (event.keyCode !== 27) {\n return;\n }\n // Fetch the previous scroll value.\n let value = this._pressData ? this._pressData.value : -1;\n // Release the mouse.\n this._releaseMouse();\n // Restore the old scroll value if possible.\n if (value !== -1) {\n this._moveThumb(value);\n }\n }\n /**\n * Handle the `'mousedown'` event for the scroll bar.\n */\n _evtMouseDown(event) {\n // Do nothing if it's not a left mouse press.\n if (event.button !== 0) {\n return;\n }\n // Send an activate request to the scroll bar. This can be\n // used by message hooks to activate something relevant.\n this.activate();\n // Do nothing if the mouse is already captured.\n if (this._pressData) {\n return;\n }\n // Find the pressed scroll bar part.\n let part = Private$2.findPart(this, event.target);\n // Do nothing if the part is not of interest.\n if (!part) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Override the mouse cursor.\n let override = Drag.overrideCursor('default');\n // Set up the press data.\n this._pressData = {\n part,\n override,\n delta: -1,\n value: -1,\n mouseX: event.clientX,\n mouseY: event.clientY\n };\n // Add the extra event listeners.\n document.addEventListener('mousemove', this, true);\n document.addEventListener('mouseup', this, true);\n document.addEventListener('keydown', this, true);\n document.addEventListener('contextmenu', this, true);\n // Handle a thumb press.\n if (part === 'thumb') {\n // Fetch the thumb node.\n let thumbNode = this.thumbNode;\n // Fetch the client rect for the thumb.\n let thumbRect = thumbNode.getBoundingClientRect();\n // Update the press data delta for the current orientation.\n if (this._orientation === 'horizontal') {\n this._pressData.delta = event.clientX - thumbRect.left;\n }\n else {\n this._pressData.delta = event.clientY - thumbRect.top;\n }\n // Add the active class to the thumb node.\n thumbNode.classList.add('lm-mod-active');\n // Store the current value in the press data.\n this._pressData.value = this._value;\n // Finished.\n return;\n }\n // Handle a track press.\n if (part === 'track') {\n // Fetch the client rect for the thumb.\n let thumbRect = this.thumbNode.getBoundingClientRect();\n // Determine the direction for the page request.\n let dir;\n if (this._orientation === 'horizontal') {\n dir = event.clientX < thumbRect.left ? 'decrement' : 'increment';\n }\n else {\n dir = event.clientY < thumbRect.top ? 'decrement' : 'increment';\n }\n // Start the repeat timer.\n this._repeatTimer = window.setTimeout(this._onRepeat, 350);\n // Emit the page requested signal.\n this._pageRequested.emit(dir);\n // Finished.\n return;\n }\n // Handle a decrement button press.\n if (part === 'decrement') {\n // Add the active class to the decrement node.\n this.decrementNode.classList.add('lm-mod-active');\n // Start the repeat timer.\n this._repeatTimer = window.setTimeout(this._onRepeat, 350);\n // Emit the step requested signal.\n this._stepRequested.emit('decrement');\n // Finished.\n return;\n }\n // Handle an increment button press.\n if (part === 'increment') {\n // Add the active class to the increment node.\n this.incrementNode.classList.add('lm-mod-active');\n // Start the repeat timer.\n this._repeatTimer = window.setTimeout(this._onRepeat, 350);\n // Emit the step requested signal.\n this._stepRequested.emit('increment');\n // Finished.\n return;\n }\n }\n /**\n * Handle the `'mousemove'` event for the scroll bar.\n */\n _evtMouseMove(event) {\n // Do nothing if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Update the mouse position.\n this._pressData.mouseX = event.clientX;\n this._pressData.mouseY = event.clientY;\n // Bail if the thumb is not being dragged.\n if (this._pressData.part !== 'thumb') {\n return;\n }\n // Get the client rect for the thumb and track.\n let thumbRect = this.thumbNode.getBoundingClientRect();\n let trackRect = this.trackNode.getBoundingClientRect();\n // Fetch the scroll geometry based on the orientation.\n let trackPos;\n let trackSpan;\n if (this._orientation === 'horizontal') {\n trackPos = event.clientX - trackRect.left - this._pressData.delta;\n trackSpan = trackRect.width - thumbRect.width;\n }\n else {\n trackPos = event.clientY - trackRect.top - this._pressData.delta;\n trackSpan = trackRect.height - thumbRect.height;\n }\n // Compute the desired value from the scroll geometry.\n let value = trackSpan === 0 ? 0 : (trackPos * this._maximum) / trackSpan;\n // Move the thumb to the computed value.\n this._moveThumb(value);\n }\n /**\n * Handle the `'mouseup'` event for the scroll bar.\n */\n _evtMouseUp(event) {\n // Do nothing if it's not a left mouse release.\n if (event.button !== 0) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Release the mouse.\n this._releaseMouse();\n }\n /**\n * Release the mouse and restore the node states.\n */\n _releaseMouse() {\n // Bail if there is no press data.\n if (!this._pressData) {\n return;\n }\n // Clear the repeat timer.\n clearTimeout(this._repeatTimer);\n this._repeatTimer = -1;\n // Clear the press data.\n this._pressData.override.dispose();\n this._pressData = null;\n // Remove the extra event listeners.\n document.removeEventListener('mousemove', this, true);\n document.removeEventListener('mouseup', this, true);\n document.removeEventListener('keydown', this, true);\n document.removeEventListener('contextmenu', this, true);\n // Remove the active classes from the nodes.\n this.thumbNode.classList.remove('lm-mod-active');\n this.decrementNode.classList.remove('lm-mod-active');\n this.incrementNode.classList.remove('lm-mod-active');\n }\n /**\n * Move the thumb to the specified position.\n */\n _moveThumb(value) {\n // Clamp the value to the allowed range.\n value = Math.max(0, Math.min(value, this._maximum));\n // Bail if the value does not change.\n if (this._value === value) {\n return;\n }\n // Update the internal value.\n this._value = value;\n // Schedule an update of the scroll bar.\n this.update();\n // Emit the thumb moved signal.\n this._thumbMoved.emit(value);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$2;\n(function (Private) {\n /**\n * Create the DOM node for a scroll bar.\n */\n function createNode() {\n let node = document.createElement('div');\n let decrement = document.createElement('div');\n let increment = document.createElement('div');\n let track = document.createElement('div');\n let thumb = document.createElement('div');\n decrement.className = 'lm-ScrollBar-button';\n increment.className = 'lm-ScrollBar-button';\n decrement.dataset['action'] = 'decrement';\n increment.dataset['action'] = 'increment';\n track.className = 'lm-ScrollBar-track';\n thumb.className = 'lm-ScrollBar-thumb';\n track.appendChild(thumb);\n node.appendChild(decrement);\n node.appendChild(track);\n node.appendChild(increment);\n return node;\n }\n Private.createNode = createNode;\n /**\n * Find the scroll bar part which contains the given target.\n */\n function findPart(scrollBar, target) {\n // Test the thumb.\n if (scrollBar.thumbNode.contains(target)) {\n return 'thumb';\n }\n // Test the track.\n if (scrollBar.trackNode.contains(target)) {\n return 'track';\n }\n // Test the decrement button.\n if (scrollBar.decrementNode.contains(target)) {\n return 'decrement';\n }\n // Test the increment button.\n if (scrollBar.incrementNode.contains(target)) {\n return 'increment';\n }\n // Indicate no match.\n return null;\n }\n Private.findPart = findPart;\n})(Private$2 || (Private$2 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A concrete layout implementation which holds a single widget.\n *\n * #### Notes\n * This class is useful for creating simple container widgets which\n * hold a single child. The child should be positioned with CSS.\n */\nclass SingletonLayout extends Layout {\n constructor() {\n super(...arguments);\n this._widget = null;\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n if (this._widget) {\n let widget = this._widget;\n this._widget = null;\n widget.dispose();\n }\n super.dispose();\n }\n /**\n * Get the child widget for the layout.\n */\n get widget() {\n return this._widget;\n }\n /**\n * Set the child widget for the layout.\n *\n * #### Notes\n * Setting the child widget will cause the old child widget to be\n * automatically disposed. If that is not desired, set the parent\n * of the old child to `null` before assigning a new child.\n */\n set widget(widget) {\n // Remove the widget from its current parent. This is a no-op\n // if the widget's parent is already the layout parent widget.\n if (widget) {\n widget.parent = this.parent;\n }\n // Bail early if the widget does not change.\n if (this._widget === widget) {\n return;\n }\n // Dispose of the old child widget.\n if (this._widget) {\n this._widget.dispose();\n }\n // Update the internal widget.\n this._widget = widget;\n // Attach the new child widget if needed.\n if (this.parent && widget) {\n this.attachWidget(widget);\n }\n }\n /**\n * Create an iterator over the widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n */\n *[Symbol.iterator]() {\n if (this._widget) {\n yield this._widget;\n }\n }\n /**\n * Remove a widget from the layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n // Bail early if the widget does not exist in the layout.\n if (this._widget !== widget) {\n return;\n }\n // Clear the internal widget.\n this._widget = null;\n // If the layout is parented, detach the widget from the DOM.\n if (this.parent) {\n this.detachWidget(widget);\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n super.init();\n for (const widget of this) {\n this.attachWidget(widget);\n }\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This method is called automatically by the single layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation adds the widgets's node to the parent's\n * node at the proper location, and sends the appropriate attach\n * messages to the widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is added to the parent's node.\n */\n attachWidget(widget) {\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This method is called automatically by the single layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation removes the widget's node from the\n * parent's node, and sends the appropriate detach messages to the\n * widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is removed from the parent's node.\n */\n detachWidget(widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout where visible widgets are stacked atop one another.\n *\n * #### Notes\n * The Z-order of the visible widgets follows their layout order.\n */\nclass StackedLayout extends PanelLayout {\n constructor(options = {}) {\n super(options);\n this._dirty = false;\n this._items = [];\n this._box = null;\n this._hiddenMode =\n options.hiddenMode !== undefined\n ? options.hiddenMode\n : Widget.HiddenMode.Display;\n }\n /**\n * The method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n get hiddenMode() {\n return this._hiddenMode;\n }\n /**\n * Set the method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n set hiddenMode(v) {\n if (this._hiddenMode === v) {\n return;\n }\n this._hiddenMode = v;\n if (this.widgets.length > 1) {\n this.widgets.forEach(w => {\n w.hiddenMode = this._hiddenMode;\n });\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the layout items.\n for (const item of this._items) {\n item.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n attachWidget(index, widget) {\n // Using transform create an additional layer in the pixel pipeline\n // to limit the number of layer, it is set only if there is more than one widget.\n if (this._hiddenMode === Widget.HiddenMode.Scale &&\n this._items.length > 0) {\n if (this._items.length === 1) {\n this.widgets[0].hiddenMode = Widget.HiddenMode.Scale;\n }\n widget.hiddenMode = Widget.HiddenMode.Scale;\n }\n else {\n widget.hiddenMode = Widget.HiddenMode.Display;\n }\n // Create and add a new layout item for the widget.\n ArrayExt.insert(this._items, index, new LayoutItem(widget));\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Move the layout item for the widget.\n ArrayExt.move(this._items, fromIndex, toIndex);\n // Post an update request for the parent widget.\n this.parent.update();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n // Remove the layout item for the widget.\n let item = ArrayExt.removeAt(this._items, index);\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Reset the z-index for the widget.\n item.widget.node.style.zIndex = '';\n // Reset the hidden mode for the widget.\n if (this._hiddenMode === Widget.HiddenMode.Scale) {\n widget.hiddenMode = Widget.HiddenMode.Display;\n // Reset the hidden mode for the first widget if necessary.\n if (this._items.length === 1) {\n this._items[0].widget.hiddenMode = Widget.HiddenMode.Display;\n }\n }\n // Dispose of the layout item.\n item.dispose();\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Set up the computed minimum size.\n let minW = 0;\n let minH = 0;\n // Update the computed minimum size.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Update the size limits for the item.\n item.fit();\n // Update the computed minimum size.\n minW = Math.max(minW, item.minWidth);\n minH = Math.max(minH, item.minHeight);\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Bail early if there are no visible items to layout.\n if (nVisible === 0) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the actual layout bounds adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Update the widget stacking order and layout geometry.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Set the z-index for the widget.\n item.widget.node.style.zIndex = `${i}`;\n // Update the item geometry.\n item.update(left, top, width, height);\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A panel where visible widgets are stacked atop one another.\n *\n * #### Notes\n * This class provides a convenience wrapper around a {@link StackedLayout}.\n */\nclass StackedPanel extends Panel {\n /**\n * Construct a new stacked panel.\n *\n * @param options - The options for initializing the panel.\n */\n constructor(options = {}) {\n super({ layout: Private$1.createLayout(options) });\n this._widgetRemoved = new Signal(this);\n this.addClass('lm-StackedPanel');\n }\n /**\n * The method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n get hiddenMode() {\n return this.layout.hiddenMode;\n }\n /**\n * Set the method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n set hiddenMode(v) {\n this.layout.hiddenMode = v;\n }\n /**\n * A signal emitted when a widget is removed from a stacked panel.\n */\n get widgetRemoved() {\n return this._widgetRemoved;\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n msg.child.addClass('lm-StackedPanel-child');\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n msg.child.removeClass('lm-StackedPanel-child');\n this._widgetRemoved.emit(msg.child);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$1;\n(function (Private) {\n /**\n * Create a stacked layout for the given panel options.\n */\n function createLayout(options) {\n return options.layout || new StackedLayout();\n }\n Private.createLayout = createLayout;\n})(Private$1 || (Private$1 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which combines a `TabBar` and a `StackedPanel`.\n *\n * #### Notes\n * This is a simple panel which handles the common case of a tab bar\n * placed next to a content area. The selected tab controls the widget\n * which is shown in the content area.\n *\n * For use cases which require more control than is provided by this\n * panel, the `TabBar` widget may be used independently.\n */\nclass TabPanel extends Widget {\n /**\n * Construct a new tab panel.\n *\n * @param options - The options for initializing the tab panel.\n */\n constructor(options = {}) {\n super();\n this._currentChanged = new Signal(this);\n this._addRequested = new Signal(this);\n this.addClass('lm-TabPanel');\n // Create the tab bar and stacked panel.\n this.tabBar = new TabBar(options);\n this.tabBar.addClass('lm-TabPanel-tabBar');\n this.stackedPanel = new StackedPanel();\n this.stackedPanel.addClass('lm-TabPanel-stackedPanel');\n // Connect the tab bar signal handlers.\n this.tabBar.tabMoved.connect(this._onTabMoved, this);\n this.tabBar.currentChanged.connect(this._onCurrentChanged, this);\n this.tabBar.tabCloseRequested.connect(this._onTabCloseRequested, this);\n this.tabBar.tabActivateRequested.connect(this._onTabActivateRequested, this);\n this.tabBar.addRequested.connect(this._onTabAddRequested, this);\n // Connect the stacked panel signal handlers.\n this.stackedPanel.widgetRemoved.connect(this._onWidgetRemoved, this);\n // Get the data related to the placement.\n this._tabPlacement = options.tabPlacement || 'top';\n let direction = Private.directionFromPlacement(this._tabPlacement);\n let orientation = Private.orientationFromPlacement(this._tabPlacement);\n // Configure the tab bar for the placement.\n this.tabBar.orientation = orientation;\n this.tabBar.dataset['placement'] = this._tabPlacement;\n // Create the box layout.\n let layout = new BoxLayout({ direction, spacing: 0 });\n // Set the stretch factors for the child widgets.\n BoxLayout.setStretch(this.tabBar, 0);\n BoxLayout.setStretch(this.stackedPanel, 1);\n // Add the child widgets to the layout.\n layout.addWidget(this.tabBar);\n layout.addWidget(this.stackedPanel);\n // Install the layout on the tab panel.\n this.layout = layout;\n }\n /**\n * A signal emitted when the current tab is changed.\n *\n * #### Notes\n * This signal is emitted when the currently selected tab is changed\n * either through user or programmatic interaction.\n *\n * Notably, this signal is not emitted when the index of the current\n * tab changes due to tabs being inserted, removed, or moved. It is\n * only emitted when the actual current tab node is changed.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * Get the index of the currently selected tab.\n *\n * #### Notes\n * This will be `-1` if no tab is selected.\n */\n get currentIndex() {\n return this.tabBar.currentIndex;\n }\n /**\n * Set the index of the currently selected tab.\n *\n * #### Notes\n * If the index is out of range, it will be set to `-1`.\n */\n set currentIndex(value) {\n this.tabBar.currentIndex = value;\n }\n /**\n * Get the currently selected widget.\n *\n * #### Notes\n * This will be `null` if there is no selected tab.\n */\n get currentWidget() {\n let title = this.tabBar.currentTitle;\n return title ? title.owner : null;\n }\n /**\n * Set the currently selected widget.\n *\n * #### Notes\n * If the widget is not in the panel, it will be set to `null`.\n */\n set currentWidget(value) {\n this.tabBar.currentTitle = value ? value.title : null;\n }\n /**\n * Get the whether the tabs are movable by the user.\n *\n * #### Notes\n * Tabs can always be moved programmatically.\n */\n get tabsMovable() {\n return this.tabBar.tabsMovable;\n }\n /**\n * Set the whether the tabs are movable by the user.\n *\n * #### Notes\n * Tabs can always be moved programmatically.\n */\n set tabsMovable(value) {\n this.tabBar.tabsMovable = value;\n }\n /**\n * Get the whether the add button is enabled.\n *\n */\n get addButtonEnabled() {\n return this.tabBar.addButtonEnabled;\n }\n /**\n * Set the whether the add button is enabled.\n *\n */\n set addButtonEnabled(value) {\n this.tabBar.addButtonEnabled = value;\n }\n /**\n * Get the tab placement for the tab panel.\n *\n * #### Notes\n * This controls the position of the tab bar relative to the content.\n */\n get tabPlacement() {\n return this._tabPlacement;\n }\n /**\n * Set the tab placement for the tab panel.\n *\n * #### Notes\n * This controls the position of the tab bar relative to the content.\n */\n set tabPlacement(value) {\n // Bail if the placement does not change.\n if (this._tabPlacement === value) {\n return;\n }\n // Update the internal value.\n this._tabPlacement = value;\n // Get the values related to the placement.\n let direction = Private.directionFromPlacement(value);\n let orientation = Private.orientationFromPlacement(value);\n // Configure the tab bar for the placement.\n this.tabBar.orientation = orientation;\n this.tabBar.dataset['placement'] = value;\n // Update the layout direction.\n this.layout.direction = direction;\n }\n /**\n * A signal emitted when the add button on a tab bar is clicked.\n *\n */\n get addRequested() {\n return this._addRequested;\n }\n /**\n * A read-only array of the widgets in the panel.\n */\n get widgets() {\n return this.stackedPanel.widgets;\n }\n /**\n * Add a widget to the end of the tab panel.\n *\n * @param widget - The widget to add to the tab panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n *\n * The widget's `title` is used to populate the tab.\n */\n addWidget(widget) {\n this.insertWidget(this.widgets.length, widget);\n }\n /**\n * Insert a widget into the tab panel at a specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into to the tab panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n *\n * The widget's `title` is used to populate the tab.\n */\n insertWidget(index, widget) {\n if (widget !== this.currentWidget) {\n widget.hide();\n }\n this.stackedPanel.insertWidget(index, widget);\n this.tabBar.insertTab(index, widget.title);\n widget.node.setAttribute('role', 'tabpanel');\n let renderer = this.tabBar.renderer;\n if (renderer instanceof TabBar.Renderer) {\n let tabId = renderer.createTabKey({\n title: widget.title,\n current: false,\n zIndex: 0\n });\n widget.node.setAttribute('aria-labelledby', tabId);\n }\n }\n /**\n * Handle the `currentChanged` signal from the tab bar.\n */\n _onCurrentChanged(sender, args) {\n // Extract the previous and current title from the args.\n let { previousIndex, previousTitle, currentIndex, currentTitle } = args;\n // Extract the widgets from the titles.\n let previousWidget = previousTitle ? previousTitle.owner : null;\n let currentWidget = currentTitle ? currentTitle.owner : null;\n // Hide the previous widget.\n if (previousWidget) {\n previousWidget.hide();\n }\n // Show the current widget.\n if (currentWidget) {\n currentWidget.show();\n }\n // Emit the `currentChanged` signal for the tab panel.\n this._currentChanged.emit({\n previousIndex,\n previousWidget,\n currentIndex,\n currentWidget\n });\n // Flush the message loop on IE and Edge to prevent flicker.\n if (Platform.IS_EDGE || Platform.IS_IE) {\n MessageLoop.flush();\n }\n }\n /**\n * Handle the `tabAddRequested` signal from the tab bar.\n */\n _onTabAddRequested(sender, args) {\n this._addRequested.emit(sender);\n }\n /**\n * Handle the `tabActivateRequested` signal from the tab bar.\n */\n _onTabActivateRequested(sender, args) {\n args.title.owner.activate();\n }\n /**\n * Handle the `tabCloseRequested` signal from the tab bar.\n */\n _onTabCloseRequested(sender, args) {\n args.title.owner.close();\n }\n /**\n * Handle the `tabMoved` signal from the tab bar.\n */\n _onTabMoved(sender, args) {\n this.stackedPanel.insertWidget(args.toIndex, args.title.owner);\n }\n /**\n * Handle the `widgetRemoved` signal from the stacked panel.\n */\n _onWidgetRemoved(sender, widget) {\n widget.node.removeAttribute('role');\n widget.node.removeAttribute('aria-labelledby');\n this.tabBar.removeTab(widget.title);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Convert a tab placement to tab bar orientation.\n */\n function orientationFromPlacement(plc) {\n return placementToOrientationMap[plc];\n }\n Private.orientationFromPlacement = orientationFromPlacement;\n /**\n * Convert a tab placement to a box layout direction.\n */\n function directionFromPlacement(plc) {\n return placementToDirectionMap[plc];\n }\n Private.directionFromPlacement = directionFromPlacement;\n /**\n * A mapping of tab placement to tab bar orientation.\n */\n const placementToOrientationMap = {\n top: 'horizontal',\n left: 'vertical',\n right: 'vertical',\n bottom: 'horizontal'\n };\n /**\n * A mapping of tab placement to box layout direction.\n */\n const placementToDirectionMap = {\n top: 'top-to-bottom',\n left: 'left-to-right',\n right: 'right-to-left',\n bottom: 'bottom-to-top'\n };\n})(Private || (Private = {}));\n\nexport { AccordionLayout, AccordionPanel, BoxEngine, BoxLayout, BoxPanel, BoxSizer, CommandPalette, ContextMenu, DockLayout, DockPanel, FocusTracker, GridLayout, Layout, LayoutItem, Menu, MenuBar, Panel, PanelLayout, ScrollBar, SingletonLayout, SplitLayout, SplitPanel, StackedLayout, StackedPanel, TabBar, TabPanel, Title, Widget };\n//# sourceMappingURL=index.es6.js.map\n","import { CommandRegistry } from '@lumino/commands';\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport { ContextMenu, Widget } from '@lumino/widgets';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$1;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private$1 || (Private$1 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module application\n */\n/**\n * A class for creating pluggable applications.\n *\n * @typeparam T - The type of the application shell.\n *\n * #### Notes\n * The `Application` class is useful when creating large, complex\n * UI applications with the ability to be safely extended by third\n * party code via plugins.\n */\nclass Application {\n /**\n * Construct a new application.\n *\n * @param options - The options for creating the application.\n */\n constructor(options) {\n this._delegate = new PromiseDelegate();\n this._plugins = new Map();\n this._services = new Map();\n this._started = false;\n this._bubblingKeydown = false;\n // Initialize the application state.\n this.commands = new CommandRegistry();\n this.contextMenu = new ContextMenu({\n commands: this.commands,\n renderer: options.contextMenuRenderer\n });\n this.shell = options.shell;\n }\n /**\n * A promise which resolves after the application has started.\n *\n * #### Notes\n * This promise will resolve after the `start()` method is called,\n * when all the bootstrapping and shell mounting work is complete.\n */\n get started() {\n return this._delegate.promise;\n }\n /**\n * Get a plugin description.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns The plugin description.\n */\n getPluginDescription(id) {\n var _a, _b;\n return (_b = (_a = this._plugins.get(id)) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : '';\n }\n /**\n * Test whether a plugin is registered with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is registered, `false` otherwise.\n */\n hasPlugin(id) {\n return this._plugins.has(id);\n }\n /**\n * Test whether a plugin is activated with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is activated, `false` otherwise.\n */\n isPluginActivated(id) {\n var _a, _b;\n return (_b = (_a = this._plugins.get(id)) === null || _a === void 0 ? void 0 : _a.activated) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * List the IDs of the plugins registered with the application.\n *\n * @returns A new array of the registered plugin IDs.\n */\n listPlugins() {\n return Array.from(this._plugins.keys());\n }\n /**\n * Register a plugin with the application.\n *\n * @param plugin - The plugin to register.\n *\n * #### Notes\n * An error will be thrown if a plugin with the same ID is already\n * registered, or if the plugin has a circular dependency.\n *\n * If the plugin provides a service which has already been provided\n * by another plugin, the new service will override the old service.\n */\n registerPlugin(plugin) {\n // Throw an error if the plugin ID is already registered.\n if (this._plugins.has(plugin.id)) {\n throw new TypeError(`Plugin '${plugin.id}' is already registered.`);\n }\n // Create the normalized plugin data.\n const data = Private.createPluginData(plugin);\n // Ensure the plugin does not cause a cyclic dependency.\n Private.ensureNoCycle(data, this._plugins, this._services);\n // Add the service token to the service map.\n if (data.provides) {\n this._services.set(data.provides, data.id);\n }\n // Add the plugin to the plugin map.\n this._plugins.set(data.id, data);\n }\n /**\n * Register multiple plugins with the application.\n *\n * @param plugins - The plugins to register.\n *\n * #### Notes\n * This calls `registerPlugin()` for each of the given plugins.\n */\n registerPlugins(plugins) {\n for (const plugin of plugins) {\n this.registerPlugin(plugin);\n }\n }\n /**\n * Deregister a plugin with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param force - Whether to deregister the plugin even if it is active.\n */\n deregisterPlugin(id, force) {\n const plugin = this._plugins.get(id);\n if (!plugin) {\n return;\n }\n if (plugin.activated && !force) {\n throw new Error(`Plugin '${id}' is still active.`);\n }\n this._plugins.delete(id);\n }\n /**\n * Activate the plugin with the given ID.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A promise which resolves when the plugin is activated\n * or rejects with an error if it cannot be activated.\n */\n async activatePlugin(id) {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n // Resolve immediately if the plugin is already activated.\n if (plugin.activated) {\n return;\n }\n // Return the pending resolver promise if it exists.\n if (plugin.promise) {\n return plugin.promise;\n }\n // Resolve the required services for the plugin.\n const required = plugin.requires.map(t => this.resolveRequiredService(t));\n // Resolve the optional services for the plugin.\n const optional = plugin.optional.map(t => this.resolveOptionalService(t));\n // Setup the resolver promise for the plugin.\n plugin.promise = Promise.all([...required, ...optional])\n .then(services => plugin.activate.apply(undefined, [this, ...services]))\n .then(service => {\n plugin.service = service;\n plugin.activated = true;\n plugin.promise = null;\n })\n .catch(error => {\n plugin.promise = null;\n throw error;\n });\n // Return the pending resolver promise.\n return plugin.promise;\n }\n /**\n * Deactivate the plugin and its downstream dependents if and only if the\n * plugin and its dependents all support `deactivate`.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A list of IDs of downstream plugins deactivated with this one.\n */\n async deactivatePlugin(id) {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n // Bail early if the plugin is not activated.\n if (!plugin.activated) {\n return [];\n }\n // Check that this plugin can deactivate.\n if (!plugin.deactivate) {\n throw new TypeError(`Plugin '${id}'#deactivate() method missing`);\n }\n // Find the optimal deactivation order for plugins downstream of this one.\n const manifest = Private.findDependents(id, this._plugins, this._services);\n const downstream = manifest.map(id => this._plugins.get(id));\n // Check that all downstream plugins can deactivate.\n for (const plugin of downstream) {\n if (!plugin.deactivate) {\n throw new TypeError(`Plugin ${plugin.id}#deactivate() method missing (depends on ${id})`);\n }\n }\n // Deactivate all downstream plugins.\n for (const plugin of downstream) {\n const services = [...plugin.requires, ...plugin.optional].map(service => {\n const id = this._services.get(service);\n return id ? this._plugins.get(id).service : null;\n });\n // Await deactivation so the next plugins only receive active services.\n await plugin.deactivate(this, ...services);\n plugin.service = null;\n plugin.activated = false;\n }\n // Remove plugin ID and return manifest of deactivated plugins.\n manifest.pop();\n return manifest;\n }\n /**\n * Resolve a required service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or rejects with an error if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the required services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveRequiredService(token) {\n // Reject the promise if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n throw new TypeError(`No provider for: ${token.name}.`);\n }\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id);\n if (!plugin.activated) {\n await this.activatePlugin(id);\n }\n return plugin.service;\n }\n /**\n * Resolve an optional service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or `null` if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the optional services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveOptionalService(token) {\n // Resolve with `null` if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n return null;\n }\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id);\n if (!plugin.activated) {\n try {\n await this.activatePlugin(id);\n }\n catch (reason) {\n console.error(reason);\n return null;\n }\n }\n return plugin.service;\n }\n /**\n * Start the application.\n *\n * @param options - The options for starting the application.\n *\n * @returns A promise which resolves when all bootstrapping work\n * is complete and the shell is mounted to the DOM.\n *\n * #### Notes\n * This should be called once by the application creator after all\n * initial plugins have been registered.\n *\n * If a plugin fails to the load, the error will be logged and the\n * other valid plugins will continue to be loaded.\n *\n * Bootstrapping the application consists of the following steps:\n * 1. Activate the startup plugins\n * 2. Wait for those plugins to activate\n * 3. Attach the shell widget to the DOM\n * 4. Add the application event listeners\n */\n start(options = {}) {\n // Return immediately if the application is already started.\n if (this._started) {\n return this._delegate.promise;\n }\n // Mark the application as started;\n this._started = true;\n this._bubblingKeydown = options.bubblingKeydown || false;\n // Parse the host ID for attaching the shell.\n const hostID = options.hostID || '';\n // Collect the ids of the startup plugins.\n const startups = Private.collectStartupPlugins(this._plugins, options);\n // Generate the activation promises.\n const promises = startups.map(id => {\n return this.activatePlugin(id).catch(error => {\n console.error(`Plugin '${id}' failed to activate.`);\n console.error(error);\n });\n });\n // Wait for the plugins to activate, then finalize startup.\n Promise.all(promises).then(() => {\n this.attachShell(hostID);\n this.addEventListeners();\n this._delegate.resolve();\n });\n // Return the pending delegate promise.\n return this._delegate.promise;\n }\n /**\n * The list of all the deferred plugins.\n */\n get deferredPlugins() {\n return Array.from(this._plugins)\n .filter(([id, plugin]) => plugin.autoStart === 'defer')\n .map(([id, plugin]) => id);\n }\n /**\n * Activate all the deferred plugins.\n *\n * @returns A promise which will resolve when each plugin is activated\n * or rejects with an error if one cannot be activated.\n */\n async activateDeferredPlugins() {\n const promises = this.deferredPlugins\n .filter(pluginId => this._plugins.get(pluginId).autoStart)\n .map(pluginId => {\n return this.activatePlugin(pluginId);\n });\n await Promise.all(promises);\n }\n /**\n * Handle the DOM events for the application.\n *\n * @param event - The DOM event sent to the application.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events registered for the application. It\n * should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'resize':\n this.evtResize(event);\n break;\n case 'keydown':\n this.evtKeydown(event);\n break;\n case 'contextmenu':\n this.evtContextMenu(event);\n break;\n }\n }\n /**\n * Attach the application shell to the DOM.\n *\n * @param id - The ID of the host node for the shell, or `''`.\n *\n * #### Notes\n * If the ID is not provided, the document body will be the host.\n *\n * A subclass may reimplement this method as needed.\n */\n attachShell(id) {\n Widget.attach(this.shell, (id && document.getElementById(id)) || document.body);\n }\n /**\n * Add the application event listeners.\n *\n * #### Notes\n * The default implementation of this method adds listeners for\n * `'keydown'` and `'resize'` events.\n *\n * A subclass may reimplement this method as needed.\n */\n addEventListeners() {\n document.addEventListener('contextmenu', this);\n document.addEventListener('keydown', this, !this._bubblingKeydown);\n window.addEventListener('resize', this);\n }\n /**\n * A method invoked on a document `'keydown'` event.\n *\n * #### Notes\n * The default implementation of this method invokes the key down\n * processing method of the application command registry.\n *\n * A subclass may reimplement this method as needed.\n */\n evtKeydown(event) {\n this.commands.processKeydownEvent(event);\n }\n /**\n * A method invoked on a document `'contextmenu'` event.\n *\n * #### Notes\n * The default implementation of this method opens the application\n * `contextMenu` at the current mouse position.\n *\n * If the application context menu has no matching content *or* if\n * the shift key is pressed, the default browser context menu will\n * be opened instead.\n *\n * A subclass may reimplement this method as needed.\n */\n evtContextMenu(event) {\n if (event.shiftKey) {\n return;\n }\n if (this.contextMenu.open(event)) {\n event.preventDefault();\n event.stopPropagation();\n }\n }\n /**\n * A method invoked on a window `'resize'` event.\n *\n * #### Notes\n * The default implementation of this method updates the shell.\n *\n * A subclass may reimplement this method as needed.\n */\n evtResize(event) {\n this.shell.update();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Create a normalized plugin data object for the given plugin.\n */\n function createPluginData(plugin) {\n var _a, _b, _c, _d;\n return {\n id: plugin.id,\n description: (_a = plugin.description) !== null && _a !== void 0 ? _a : '',\n service: null,\n promise: null,\n activated: false,\n activate: plugin.activate,\n deactivate: (_b = plugin.deactivate) !== null && _b !== void 0 ? _b : null,\n provides: (_c = plugin.provides) !== null && _c !== void 0 ? _c : null,\n autoStart: (_d = plugin.autoStart) !== null && _d !== void 0 ? _d : false,\n requires: plugin.requires ? plugin.requires.slice() : [],\n optional: plugin.optional ? plugin.optional.slice() : []\n };\n }\n Private.createPluginData = createPluginData;\n /**\n * Ensure no cycle is present in the plugin resolution graph.\n *\n * If a cycle is detected, an error will be thrown.\n */\n function ensureNoCycle(plugin, plugins, services) {\n const dependencies = [...plugin.requires, ...plugin.optional];\n const visit = (token) => {\n if (token === plugin.provides) {\n return true;\n }\n const id = services.get(token);\n if (!id) {\n return false;\n }\n const visited = plugins.get(id);\n const dependencies = [...visited.requires, ...visited.optional];\n if (dependencies.length === 0) {\n return false;\n }\n trace.push(id);\n if (dependencies.some(visit)) {\n return true;\n }\n trace.pop();\n return false;\n };\n // Bail early if there cannot be a cycle.\n if (!plugin.provides || dependencies.length === 0) {\n return;\n }\n // Setup a stack to trace service resolution.\n const trace = [plugin.id];\n // Throw an exception if a cycle is present.\n if (dependencies.some(visit)) {\n throw new ReferenceError(`Cycle detected: ${trace.join(' -> ')}.`);\n }\n }\n Private.ensureNoCycle = ensureNoCycle;\n /**\n * Find dependents in deactivation order.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param plugins - The map containing all plugins.\n *\n * @param services - The map containing all services.\n *\n * @returns A list of dependent plugin IDs in order of deactivation\n *\n * #### Notes\n * The final item of the returned list is always the plugin of interest.\n */\n function findDependents(id, plugins, services) {\n const edges = new Array();\n const add = (id) => {\n const plugin = plugins.get(id);\n // FIXME In the case of missing optional dependencies, we may consider\n // deactivating and reactivating the plugin without the missing service.\n const dependencies = [...plugin.requires, ...plugin.optional];\n edges.push(...dependencies.reduce((acc, dep) => {\n const service = services.get(dep);\n if (service) {\n // An edge is oriented from dependent to provider.\n acc.push([id, service]);\n }\n return acc;\n }, []));\n };\n for (const id of plugins.keys()) {\n add(id);\n }\n // Filter edges\n // - Get all packages that dependent on the package to be deactivated\n const newEdges = edges.filter(edge => edge[1] === id);\n let oldSize = 0;\n while (newEdges.length > oldSize) {\n const previousSize = newEdges.length;\n // Get all packages that dependent on packages that will be deactivated\n const packagesOfInterest = new Set(newEdges.map(edge => edge[0]));\n for (const poi of packagesOfInterest) {\n edges\n .filter(edge => edge[1] === poi)\n .forEach(edge => {\n // We check it is not already included to deal with circular dependencies\n if (!newEdges.includes(edge)) {\n newEdges.push(edge);\n }\n });\n }\n oldSize = previousSize;\n }\n const sorted = topologicSort(newEdges);\n const index = sorted.findIndex(candidate => candidate === id);\n if (index === -1) {\n return [id];\n }\n return sorted.slice(0, index + 1);\n }\n Private.findDependents = findDependents;\n /**\n * Collect the IDs of the plugins to activate on startup.\n */\n function collectStartupPlugins(plugins, options) {\n // Create a set to hold the plugin IDs.\n const collection = new Set();\n // Collect the auto-start (non deferred) plugins.\n for (const id of plugins.keys()) {\n if (plugins.get(id).autoStart === true) {\n collection.add(id);\n }\n }\n // Add the startup plugins.\n if (options.startPlugins) {\n for (const id of options.startPlugins) {\n collection.add(id);\n }\n }\n // Remove the ignored plugins.\n if (options.ignorePlugins) {\n for (const id of options.ignorePlugins) {\n collection.delete(id);\n }\n }\n // Return the collected startup plugins.\n return Array.from(collection);\n }\n Private.collectStartupPlugins = collectStartupPlugins;\n})(Private || (Private = {}));\n\nexport { Application };\n//# sourceMappingURL=index.es6.js.map\n","/**\n * A simple router.\n */\nexport class Router {\n constructor() {\n this._routes = [];\n }\n /**\n * Add a new GET route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n get(pattern, callback) {\n this._add('GET', pattern, callback);\n }\n /**\n * Add a new PUT route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n put(pattern, callback) {\n this._add('PUT', pattern, callback);\n }\n /**\n * Add a new POST route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n post(pattern, callback) {\n this._add('POST', pattern, callback);\n }\n /**\n * Add a new PATCH route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n patch(pattern, callback) {\n this._add('PATCH', pattern, callback);\n }\n /**\n * Add a new DELETE route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n delete(pattern, callback) {\n this._add('DELETE', pattern, callback);\n }\n /**\n * Route a request.\n *\n * @param req The request to route.\n */\n async route(req) {\n const url = new URL(req.url);\n const { method } = req;\n const { pathname } = url;\n for (const r of this._routes) {\n if (r.method !== method) {\n continue;\n }\n const match = pathname.match(r.pattern);\n if (!match) {\n continue;\n }\n const matches = match.slice(1);\n let body;\n if (r.method === 'PATCH' || r.method === 'PUT' || r.method === 'POST') {\n try {\n body = JSON.parse(await req.text());\n }\n catch {\n body = undefined;\n }\n }\n return r.callback.call(null, {\n pathname,\n body,\n query: Object.fromEntries(url.searchParams),\n }, ...matches);\n }\n throw new Error('Cannot route ' + req.method + ' ' + req.url);\n }\n /**\n * Add a new route.\n *\n * @param method The method\n * @param pattern The pattern\n * @param callback The callback\n */\n _add(method, pattern, callback) {\n if (typeof pattern === 'string') {\n pattern = new RegExp(pattern);\n }\n this._routes.push({\n method,\n pattern,\n callback,\n });\n }\n}\n//# sourceMappingURL=router.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { ServerConnection, ServiceManager } from '@jupyterlab/services';\nimport { Application } from '@lumino/application';\nimport { Stream } from '@lumino/signaling';\nimport { WebSocket } from 'mock-socket';\nimport { Router } from './router';\n/**\n * Mock the Event Manager for now\n */\nclass MockEventManager {\n constructor(options) {\n this._stream = new Stream(this);\n this._serverSettings = options.serverSettings;\n }\n async emit(event) {\n // no-op\n }\n dispose() {\n // no-op\n }\n get isDisposed() {\n return true;\n }\n get stream() {\n return this._stream;\n }\n get serverSettings() {\n return this._serverSettings;\n }\n}\n/**\n * Server is the main application class. It is instantiated once and shared.\n */\nexport class JupyterLiteServer extends Application {\n /**\n * Construct a new JupyterLite object.\n *\n * @param options The instantiation options for a JupyterLiteServer application.\n */\n constructor(options) {\n var _a;\n super(options);\n /**\n * The name of the application.\n */\n this.name = 'JupyterLite Server';\n /**\n * A namespace/prefix plugins may use to denote their provenance.\n */\n this.namespace = this.name;\n /**\n * The version of the application.\n */\n this.version = 'unknown';\n this._router = new Router();\n const serverSettings = {\n ...ServerConnection.makeSettings(),\n WebSocket,\n fetch: (_a = this.fetch.bind(this)) !== null && _a !== void 0 ? _a : undefined,\n };\n this._serviceManager = new ServiceManager({\n standby: 'never',\n serverSettings,\n events: new MockEventManager({ serverSettings }),\n });\n }\n /**\n * Get the underlying `Router` instance.\n */\n get router() {\n return this._router;\n }\n /**\n * Get the underlying lite service manager for this app.\n */\n get serviceManager() {\n return this._serviceManager;\n }\n /**\n * Handle an incoming request from the client.\n *\n * @param req The incoming request\n * @param init The optional init request\n */\n async fetch(req, init) {\n if (!(req instanceof Request)) {\n throw Error('Request info is not a Request');\n }\n return this._router.route(req);\n }\n /**\n * Attach the application shell to the DOM.\n *\n * @param id - The id of the host node for the shell, or `''`.\n *\n * #### Notes\n * For this server application there is no shell to attach\n */\n attachShell(id) {\n // no-op\n }\n /**\n * A method invoked on a window `'resize'` event.\n *\n * #### Notes\n * For this server application there is no shell to update\n */\n evtResize(event) {\n // no-op\n }\n /**\n * Register plugins from a plugin module.\n *\n * @param mod - The plugin module to register.\n */\n registerPluginModule(mod) {\n let data = mod.default;\n // Handle commonjs exports.\n if (!Object.prototype.hasOwnProperty.call(mod, '__esModule')) {\n data = mod;\n }\n if (!Array.isArray(data)) {\n data = [data];\n }\n data.forEach((item) => {\n try {\n this.registerPlugin(item);\n }\n catch (error) {\n console.error(error);\n }\n });\n }\n /**\n * Register the plugins from multiple plugin modules.\n *\n * @param mods - The plugin modules to register.\n */\n registerPluginModules(mods) {\n mods.forEach((mod) => {\n this.registerPluginModule(mod);\n });\n }\n}\n//# sourceMappingURL=app.js.map","import { PromiseDelegate } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { WORKER_NAME } from './tokens';\nexport class ServiceWorkerManager {\n constructor(options) {\n var _a;\n this._registration = null;\n this._registrationChanged = new Signal(this);\n this._ready = new PromiseDelegate();\n const workerUrl = (_a = options === null || options === void 0 ? void 0 : options.workerUrl) !== null && _a !== void 0 ? _a : URLExt.join(PageConfig.getBaseUrl(), WORKER_NAME);\n void this.initialize(workerUrl).catch(console.warn);\n }\n /**\n * A signal emitted when the registration changes.\n */\n get registrationChanged() {\n return this._registrationChanged;\n }\n /**\n * Whether the ServiceWorker is enabled or not.\n */\n get enabled() {\n return this._registration !== null;\n }\n get ready() {\n return this._ready.promise;\n }\n async initialize(workerUrl) {\n const { serviceWorker } = navigator;\n let registration = null;\n if (!serviceWorker) {\n console.warn('ServiceWorkers not supported in this browser');\n }\n else if (serviceWorker.controller) {\n registration =\n (await serviceWorker.getRegistration(serviceWorker.controller.scriptURL)) ||\n null;\n console.info('JupyterLite ServiceWorker was already registered');\n }\n if (!registration && serviceWorker) {\n try {\n console.info('Registering new JupyterLite ServiceWorker', workerUrl);\n registration = await serviceWorker.register(workerUrl);\n console.info('JupyterLite ServiceWorker was sucessfully registered');\n }\n catch (err) {\n console.warn(err);\n console.warn(`JupyterLite ServiceWorker registration unexpectedly failed: ${err}`);\n }\n }\n this.setRegistration(registration);\n if (!registration) {\n this._ready.reject(void 0);\n }\n else {\n this._ready.resolve(void 0);\n }\n }\n setRegistration(registration) {\n this._registration = registration;\n this._registrationChanged.emit(this._registration);\n }\n}\n//# sourceMappingURL=service-manager.js.map","\"use strict\";\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// \n/**\n * The name of the cache\n */\nconst CACHE = 'precache';\n/**\n * Communication channel for drive access\n */\nconst broadcast = new BroadcastChannel('/api/drive.v1');\n/**\n * Install event listeners\n */\nself.addEventListener('install', onInstall);\nself.addEventListener('activate', onActivate);\nself.addEventListener('fetch', onFetch);\n// Event handlers\n/**\n * Handle installation with the cache\n */\nfunction onInstall(event) {\n void self.skipWaiting();\n event.waitUntil(cacheAll());\n}\n/**\n * Handle activation.\n */\nfunction onActivate(event) {\n event.waitUntil(self.clients.claim());\n}\n/**\n * Handle fetching a single resource.\n */\nasync function onFetch(event) {\n const { request } = event;\n const url = new URL(event.request.url);\n let responsePromise = null;\n if (shouldBroadcast(url)) {\n responsePromise = broadcastOne(request);\n }\n else if (!shouldDrop(request, url)) {\n responsePromise = maybeFromCache(event);\n }\n if (responsePromise) {\n event.respondWith(responsePromise);\n }\n}\n// utilities\n/** Get a cached response, and update cache. */\nasync function maybeFromCache(event) {\n const { request } = event;\n let response = await fromCache(request);\n if (response) {\n event.waitUntil(refetch(request));\n }\n else {\n response = await fetch(request);\n event.waitUntil(updateCache(request, response.clone()));\n }\n return response;\n}\n/**\n * Restore a response from the cache based on the request.\n */\nasync function fromCache(request) {\n const cache = await openCache();\n const response = await cache.match(request);\n if (!response || response.status === 404) {\n return null;\n }\n return response;\n}\n/**\n * This is where we call the server to get the newest version of the\n * file to use the next time we show view\n */\nasync function refetch(request) {\n const fromServer = await fetch(request);\n await updateCache(request, fromServer);\n return fromServer;\n}\n/**\n * Whether a given URL should be broadcast\n */\nfunction shouldBroadcast(url) {\n return url.origin === location.origin && url.pathname.includes('/api/drive');\n}\n/**\n * Whether the fallback behavior should be used\n */\nfunction shouldDrop(request, url) {\n return (request.method !== 'GET' ||\n url.origin.match(/^http/) === null ||\n url.pathname.includes('/api/'));\n}\n/**\n * Forward request to main using the broadcast channel\n */\nasync function broadcastOne(request) {\n const promise = new Promise((resolve) => {\n broadcast.onmessage = (event) => {\n resolve(new Response(JSON.stringify(event.data)));\n };\n });\n const message = await request.json();\n // Mark message as being for broadcast.ts\n // This makes sure we won't get problems with messages\n // across tabs with multiple notebook tabs open\n message.receiver = 'broadcast.ts';\n broadcast.postMessage(message);\n return await promise;\n}\nasync function openCache() {\n return await caches.open(CACHE);\n}\n/**\n * Cache a request/response pair.\n */\nasync function updateCache(request, response) {\n const cache = await openCache();\n return cache.put(request, response);\n}\n/**\n * Add all to the cache\n *\n * this is where we should (try to) add all relevant files\n */\nasync function cacheAll() {\n const cache = await openCache();\n return await cache.addAll([]);\n}\n//# sourceMappingURL=service-worker.js.map","import { Token } from '@lumino/coreutils';\nimport SW_URL from './service-worker?text';\n/**\n * The token for the ServiceWorker.\n */\nexport const IServiceWorkerManager = new Token('@jupyterlite/server-extension:IServiceWorkerManager');\nexport const WORKER_NAME = `${SW_URL}`.split('/').slice(-1)[0];\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nfunction* chain(...objects) {\n for (const object of objects) {\n yield* object;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nfunction* empty() {\n return;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nfunction* enumerate(object, start = 0) {\n for (const value of object) {\n yield [start++, value];\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* filter(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nfunction find(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nfunction findIndex(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nfunction min(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nfunction max(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nfunction minmax(object, fn) {\n let empty = true;\n let vmin;\n let vmax;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n }\n else if (fn(value, vmin) < 0) {\n vmin = value;\n }\n else if (fn(value, vmax) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin, vmax];\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nfunction toArray(object) {\n return Array.from(object);\n}\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nfunction toObject(object) {\n const result = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nfunction each(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nfunction every(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nfunction some(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* map(object, fn) {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nfunction* range(start, stop, step) {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n }\n else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nfunction reduce(object, fn, initial) {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n // Setup the initial accumlated value.\n let accumulator;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n }\n else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n // Iterate the rest of the values, updating the accumulator.\n let next;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n // Return the final accumulated value.\n return accumulator;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nfunction* repeat(value, count) {\n while (0 < count--) {\n yield value;\n }\n}\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nfunction* once(value) {\n yield value;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nfunction* retro(object) {\n if (typeof object.retro === 'function') {\n yield* object.retro();\n }\n else {\n for (let index = object.length - 1; index > -1; index--) {\n yield object[index];\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nfunction* stride(object, step) {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nfunction* take(object, count) {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nfunction* zip(...objects) {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n\nexport { ArrayExt, StringExt, chain, each, empty, enumerate, every, filter, find, findIndex, map, max, min, minmax, once, range, reduce, repeat, retro, some, stride, take, toArray, toObject, topologicSort, zip };\n//# sourceMappingURL=index.es6.js.map\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","import { find, ArrayExt } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nclass Signal {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender) {\n this.sender = sender;\n }\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot, thisArg) {\n return Private.connect(this, slot, thisArg);\n }\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot, thisArg) {\n return Private.disconnect(this, slot, thisArg);\n }\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args) {\n Private.emit(this, args);\n }\n}\n/**\n * The namespace for the `Signal` class statics.\n */\n(function (Signal) {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectBetween(sender, receiver) {\n Private.disconnectBetween(sender, receiver);\n }\n Signal.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n Private.disconnectSender(sender);\n }\n Signal.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectReceiver(receiver) {\n Private.disconnectReceiver(receiver);\n }\n Signal.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectAll(object) {\n Private.disconnectAll(object);\n }\n Signal.disconnectAll = disconnectAll;\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n function clearData(object) {\n Private.disconnectAll(object);\n }\n Signal.clearData = clearData;\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return Private.exceptionHandler;\n }\n Signal.getExceptionHandler = getExceptionHandler;\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n Signal.setExceptionHandler = setExceptionHandler;\n})(Signal || (Signal = {}));\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nclass Stream extends Signal {\n constructor() {\n super(...arguments);\n this._pending = new PromiseDelegate();\n }\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator]() {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n }\n catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args) {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n /**\n * Stop the stream's async iteration.\n */\n stop() {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The signal exception handler function.\n */\n Private.exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n function connect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n // Indicate a successful connection.\n return true;\n }\n Private.connect = connect;\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n function disconnect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver);\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n // Indicate a successful disconnection.\n return true;\n }\n Private.disconnect = disconnect;\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectBetween(sender, receiver) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n Private.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver));\n }\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n Private.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectReceiver(receiver) {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender));\n }\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n Private.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n function disconnectAll(object) {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n Private.disconnectAll = disconnectAll;\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n function emit(signal, args) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n Private.emit = emit;\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap();\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap();\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(connections, signal, slot, thisArg) {\n return find(connections, connection => connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg);\n }\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection, args) {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal.sender, args);\n }\n catch (err) {\n Private.exceptionHandler(err);\n }\n }\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection) {\n return connection.signal === null;\n }\n})(Private || (Private = {}));\n\nexport { Signal, Stream };\n//# sourceMappingURL=index.es6.js.map\n","'use strict';\n\n/**\n * @param typeMap [Object] Map of MIME type -> Array[extensions]\n * @param ...\n */\nfunction Mime() {\n this._types = Object.create(null);\n this._extensions = Object.create(null);\n\n for (let i = 0; i < arguments.length; i++) {\n this.define(arguments[i]);\n }\n\n this.define = this.define.bind(this);\n this.getType = this.getType.bind(this);\n this.getExtension = this.getExtension.bind(this);\n}\n\n/**\n * Define mimetype -> extension mappings. Each key is a mime-type that maps\n * to an array of extensions associated with the type. The first extension is\n * used as the default extension for the type.\n *\n * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});\n *\n * If a type declares an extension that has already been defined, an error will\n * be thrown. To suppress this error and force the extension to be associated\n * with the new type, pass `force`=true. Alternatively, you may prefix the\n * extension with \"*\" to map the type to extension, without mapping the\n * extension to the type.\n *\n * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});\n *\n *\n * @param map (Object) type definitions\n * @param force (Boolean) if true, force overriding of existing definitions\n */\nMime.prototype.define = function(typeMap, force) {\n for (let type in typeMap) {\n let extensions = typeMap[type].map(function(t) {\n return t.toLowerCase();\n });\n type = type.toLowerCase();\n\n for (let i = 0; i < extensions.length; i++) {\n const ext = extensions[i];\n\n // '*' prefix = not the preferred type for this extension. So fixup the\n // extension, and skip it.\n if (ext[0] === '*') {\n continue;\n }\n\n if (!force && (ext in this._types)) {\n throw new Error(\n 'Attempt to change mapping for \"' + ext +\n '\" extension from \"' + this._types[ext] + '\" to \"' + type +\n '\". Pass `force=true` to allow this, otherwise remove \"' + ext +\n '\" from the list of extensions for \"' + type + '\".'\n );\n }\n\n this._types[ext] = type;\n }\n\n // Use first extension as default\n if (force || !this._extensions[type]) {\n const ext = extensions[0];\n this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);\n }\n }\n};\n\n/**\n * Lookup a mime type based on extension\n */\nMime.prototype.getType = function(path) {\n path = String(path);\n let last = path.replace(/^.*[/\\\\]/, '').toLowerCase();\n let ext = last.replace(/^.*\\./, '').toLowerCase();\n\n let hasPath = last.length < path.length;\n let hasDot = ext.length < last.length - 1;\n\n return (hasDot || !hasPath) && this._types[ext] || null;\n};\n\n/**\n * Return file extension associated with a mime type\n */\nMime.prototype.getExtension = function(type) {\n type = /^\\s*([^;\\s]*)/.test(type) && RegExp.$1;\n return type && this._extensions[type.toLowerCase()] || null;\n};\n\nmodule.exports = Mime;\n","'use strict';\n\nlet Mime = require('./Mime');\nmodule.exports = new Mime(require('./types/standard'), require('./types/other'));\n","module.exports = {\"application/prs.cww\":[\"cww\"],\"application/vnd.1000minds.decision-model+xml\":[\"1km\"],\"application/vnd.3gpp.pic-bw-large\":[\"plb\"],\"application/vnd.3gpp.pic-bw-small\":[\"psb\"],\"application/vnd.3gpp.pic-bw-var\":[\"pvb\"],\"application/vnd.3gpp2.tcap\":[\"tcap\"],\"application/vnd.3m.post-it-notes\":[\"pwn\"],\"application/vnd.accpac.simply.aso\":[\"aso\"],\"application/vnd.accpac.simply.imp\":[\"imp\"],\"application/vnd.acucobol\":[\"acu\"],\"application/vnd.acucorp\":[\"atc\",\"acutc\"],\"application/vnd.adobe.air-application-installer-package+zip\":[\"air\"],\"application/vnd.adobe.formscentral.fcdt\":[\"fcdt\"],\"application/vnd.adobe.fxp\":[\"fxp\",\"fxpl\"],\"application/vnd.adobe.xdp+xml\":[\"xdp\"],\"application/vnd.adobe.xfdf\":[\"xfdf\"],\"application/vnd.ahead.space\":[\"ahead\"],\"application/vnd.airzip.filesecure.azf\":[\"azf\"],\"application/vnd.airzip.filesecure.azs\":[\"azs\"],\"application/vnd.amazon.ebook\":[\"azw\"],\"application/vnd.americandynamics.acc\":[\"acc\"],\"application/vnd.amiga.ami\":[\"ami\"],\"application/vnd.android.package-archive\":[\"apk\"],\"application/vnd.anser-web-certificate-issue-initiation\":[\"cii\"],\"application/vnd.anser-web-funds-transfer-initiation\":[\"fti\"],\"application/vnd.antix.game-component\":[\"atx\"],\"application/vnd.apple.installer+xml\":[\"mpkg\"],\"application/vnd.apple.keynote\":[\"key\"],\"application/vnd.apple.mpegurl\":[\"m3u8\"],\"application/vnd.apple.numbers\":[\"numbers\"],\"application/vnd.apple.pages\":[\"pages\"],\"application/vnd.apple.pkpass\":[\"pkpass\"],\"application/vnd.aristanetworks.swi\":[\"swi\"],\"application/vnd.astraea-software.iota\":[\"iota\"],\"application/vnd.audiograph\":[\"aep\"],\"application/vnd.balsamiq.bmml+xml\":[\"bmml\"],\"application/vnd.blueice.multipass\":[\"mpm\"],\"application/vnd.bmi\":[\"bmi\"],\"application/vnd.businessobjects\":[\"rep\"],\"application/vnd.chemdraw+xml\":[\"cdxml\"],\"application/vnd.chipnuts.karaoke-mmd\":[\"mmd\"],\"application/vnd.cinderella\":[\"cdy\"],\"application/vnd.citationstyles.style+xml\":[\"csl\"],\"application/vnd.claymore\":[\"cla\"],\"application/vnd.cloanto.rp9\":[\"rp9\"],\"application/vnd.clonk.c4group\":[\"c4g\",\"c4d\",\"c4f\",\"c4p\",\"c4u\"],\"application/vnd.cluetrust.cartomobile-config\":[\"c11amc\"],\"application/vnd.cluetrust.cartomobile-config-pkg\":[\"c11amz\"],\"application/vnd.commonspace\":[\"csp\"],\"application/vnd.contact.cmsg\":[\"cdbcmsg\"],\"application/vnd.cosmocaller\":[\"cmc\"],\"application/vnd.crick.clicker\":[\"clkx\"],\"application/vnd.crick.clicker.keyboard\":[\"clkk\"],\"application/vnd.crick.clicker.palette\":[\"clkp\"],\"application/vnd.crick.clicker.template\":[\"clkt\"],\"application/vnd.crick.clicker.wordbank\":[\"clkw\"],\"application/vnd.criticaltools.wbs+xml\":[\"wbs\"],\"application/vnd.ctc-posml\":[\"pml\"],\"application/vnd.cups-ppd\":[\"ppd\"],\"application/vnd.curl.car\":[\"car\"],\"application/vnd.curl.pcurl\":[\"pcurl\"],\"application/vnd.dart\":[\"dart\"],\"application/vnd.data-vision.rdz\":[\"rdz\"],\"application/vnd.dbf\":[\"dbf\"],\"application/vnd.dece.data\":[\"uvf\",\"uvvf\",\"uvd\",\"uvvd\"],\"application/vnd.dece.ttml+xml\":[\"uvt\",\"uvvt\"],\"application/vnd.dece.unspecified\":[\"uvx\",\"uvvx\"],\"application/vnd.dece.zip\":[\"uvz\",\"uvvz\"],\"application/vnd.denovo.fcselayout-link\":[\"fe_launch\"],\"application/vnd.dna\":[\"dna\"],\"application/vnd.dolby.mlp\":[\"mlp\"],\"application/vnd.dpgraph\":[\"dpg\"],\"application/vnd.dreamfactory\":[\"dfac\"],\"application/vnd.ds-keypoint\":[\"kpxx\"],\"application/vnd.dvb.ait\":[\"ait\"],\"application/vnd.dvb.service\":[\"svc\"],\"application/vnd.dynageo\":[\"geo\"],\"application/vnd.ecowin.chart\":[\"mag\"],\"application/vnd.enliven\":[\"nml\"],\"application/vnd.epson.esf\":[\"esf\"],\"application/vnd.epson.msf\":[\"msf\"],\"application/vnd.epson.quickanime\":[\"qam\"],\"application/vnd.epson.salt\":[\"slt\"],\"application/vnd.epson.ssf\":[\"ssf\"],\"application/vnd.eszigno3+xml\":[\"es3\",\"et3\"],\"application/vnd.ezpix-album\":[\"ez2\"],\"application/vnd.ezpix-package\":[\"ez3\"],\"application/vnd.fdf\":[\"fdf\"],\"application/vnd.fdsn.mseed\":[\"mseed\"],\"application/vnd.fdsn.seed\":[\"seed\",\"dataless\"],\"application/vnd.flographit\":[\"gph\"],\"application/vnd.fluxtime.clip\":[\"ftc\"],\"application/vnd.framemaker\":[\"fm\",\"frame\",\"maker\",\"book\"],\"application/vnd.frogans.fnc\":[\"fnc\"],\"application/vnd.frogans.ltf\":[\"ltf\"],\"application/vnd.fsc.weblaunch\":[\"fsc\"],\"application/vnd.fujitsu.oasys\":[\"oas\"],\"application/vnd.fujitsu.oasys2\":[\"oa2\"],\"application/vnd.fujitsu.oasys3\":[\"oa3\"],\"application/vnd.fujitsu.oasysgp\":[\"fg5\"],\"application/vnd.fujitsu.oasysprs\":[\"bh2\"],\"application/vnd.fujixerox.ddd\":[\"ddd\"],\"application/vnd.fujixerox.docuworks\":[\"xdw\"],\"application/vnd.fujixerox.docuworks.binder\":[\"xbd\"],\"application/vnd.fuzzysheet\":[\"fzs\"],\"application/vnd.genomatix.tuxedo\":[\"txd\"],\"application/vnd.geogebra.file\":[\"ggb\"],\"application/vnd.geogebra.tool\":[\"ggt\"],\"application/vnd.geometry-explorer\":[\"gex\",\"gre\"],\"application/vnd.geonext\":[\"gxt\"],\"application/vnd.geoplan\":[\"g2w\"],\"application/vnd.geospace\":[\"g3w\"],\"application/vnd.gmx\":[\"gmx\"],\"application/vnd.google-apps.document\":[\"gdoc\"],\"application/vnd.google-apps.presentation\":[\"gslides\"],\"application/vnd.google-apps.spreadsheet\":[\"gsheet\"],\"application/vnd.google-earth.kml+xml\":[\"kml\"],\"application/vnd.google-earth.kmz\":[\"kmz\"],\"application/vnd.grafeq\":[\"gqf\",\"gqs\"],\"application/vnd.groove-account\":[\"gac\"],\"application/vnd.groove-help\":[\"ghf\"],\"application/vnd.groove-identity-message\":[\"gim\"],\"application/vnd.groove-injector\":[\"grv\"],\"application/vnd.groove-tool-message\":[\"gtm\"],\"application/vnd.groove-tool-template\":[\"tpl\"],\"application/vnd.groove-vcard\":[\"vcg\"],\"application/vnd.hal+xml\":[\"hal\"],\"application/vnd.handheld-entertainment+xml\":[\"zmm\"],\"application/vnd.hbci\":[\"hbci\"],\"application/vnd.hhe.lesson-player\":[\"les\"],\"application/vnd.hp-hpgl\":[\"hpgl\"],\"application/vnd.hp-hpid\":[\"hpid\"],\"application/vnd.hp-hps\":[\"hps\"],\"application/vnd.hp-jlyt\":[\"jlt\"],\"application/vnd.hp-pcl\":[\"pcl\"],\"application/vnd.hp-pclxl\":[\"pclxl\"],\"application/vnd.hydrostatix.sof-data\":[\"sfd-hdstx\"],\"application/vnd.ibm.minipay\":[\"mpy\"],\"application/vnd.ibm.modcap\":[\"afp\",\"listafp\",\"list3820\"],\"application/vnd.ibm.rights-management\":[\"irm\"],\"application/vnd.ibm.secure-container\":[\"sc\"],\"application/vnd.iccprofile\":[\"icc\",\"icm\"],\"application/vnd.igloader\":[\"igl\"],\"application/vnd.immervision-ivp\":[\"ivp\"],\"application/vnd.immervision-ivu\":[\"ivu\"],\"application/vnd.insors.igm\":[\"igm\"],\"application/vnd.intercon.formnet\":[\"xpw\",\"xpx\"],\"application/vnd.intergeo\":[\"i2g\"],\"application/vnd.intu.qbo\":[\"qbo\"],\"application/vnd.intu.qfx\":[\"qfx\"],\"application/vnd.ipunplugged.rcprofile\":[\"rcprofile\"],\"application/vnd.irepository.package+xml\":[\"irp\"],\"application/vnd.is-xpr\":[\"xpr\"],\"application/vnd.isac.fcs\":[\"fcs\"],\"application/vnd.jam\":[\"jam\"],\"application/vnd.jcp.javame.midlet-rms\":[\"rms\"],\"application/vnd.jisp\":[\"jisp\"],\"application/vnd.joost.joda-archive\":[\"joda\"],\"application/vnd.kahootz\":[\"ktz\",\"ktr\"],\"application/vnd.kde.karbon\":[\"karbon\"],\"application/vnd.kde.kchart\":[\"chrt\"],\"application/vnd.kde.kformula\":[\"kfo\"],\"application/vnd.kde.kivio\":[\"flw\"],\"application/vnd.kde.kontour\":[\"kon\"],\"application/vnd.kde.kpresenter\":[\"kpr\",\"kpt\"],\"application/vnd.kde.kspread\":[\"ksp\"],\"application/vnd.kde.kword\":[\"kwd\",\"kwt\"],\"application/vnd.kenameaapp\":[\"htke\"],\"application/vnd.kidspiration\":[\"kia\"],\"application/vnd.kinar\":[\"kne\",\"knp\"],\"application/vnd.koan\":[\"skp\",\"skd\",\"skt\",\"skm\"],\"application/vnd.kodak-descriptor\":[\"sse\"],\"application/vnd.las.las+xml\":[\"lasxml\"],\"application/vnd.llamagraphics.life-balance.desktop\":[\"lbd\"],\"application/vnd.llamagraphics.life-balance.exchange+xml\":[\"lbe\"],\"application/vnd.lotus-1-2-3\":[\"123\"],\"application/vnd.lotus-approach\":[\"apr\"],\"application/vnd.lotus-freelance\":[\"pre\"],\"application/vnd.lotus-notes\":[\"nsf\"],\"application/vnd.lotus-organizer\":[\"org\"],\"application/vnd.lotus-screencam\":[\"scm\"],\"application/vnd.lotus-wordpro\":[\"lwp\"],\"application/vnd.macports.portpkg\":[\"portpkg\"],\"application/vnd.mapbox-vector-tile\":[\"mvt\"],\"application/vnd.mcd\":[\"mcd\"],\"application/vnd.medcalcdata\":[\"mc1\"],\"application/vnd.mediastation.cdkey\":[\"cdkey\"],\"application/vnd.mfer\":[\"mwf\"],\"application/vnd.mfmp\":[\"mfm\"],\"application/vnd.micrografx.flo\":[\"flo\"],\"application/vnd.micrografx.igx\":[\"igx\"],\"application/vnd.mif\":[\"mif\"],\"application/vnd.mobius.daf\":[\"daf\"],\"application/vnd.mobius.dis\":[\"dis\"],\"application/vnd.mobius.mbk\":[\"mbk\"],\"application/vnd.mobius.mqy\":[\"mqy\"],\"application/vnd.mobius.msl\":[\"msl\"],\"application/vnd.mobius.plc\":[\"plc\"],\"application/vnd.mobius.txf\":[\"txf\"],\"application/vnd.mophun.application\":[\"mpn\"],\"application/vnd.mophun.certificate\":[\"mpc\"],\"application/vnd.mozilla.xul+xml\":[\"xul\"],\"application/vnd.ms-artgalry\":[\"cil\"],\"application/vnd.ms-cab-compressed\":[\"cab\"],\"application/vnd.ms-excel\":[\"xls\",\"xlm\",\"xla\",\"xlc\",\"xlt\",\"xlw\"],\"application/vnd.ms-excel.addin.macroenabled.12\":[\"xlam\"],\"application/vnd.ms-excel.sheet.binary.macroenabled.12\":[\"xlsb\"],\"application/vnd.ms-excel.sheet.macroenabled.12\":[\"xlsm\"],\"application/vnd.ms-excel.template.macroenabled.12\":[\"xltm\"],\"application/vnd.ms-fontobject\":[\"eot\"],\"application/vnd.ms-htmlhelp\":[\"chm\"],\"application/vnd.ms-ims\":[\"ims\"],\"application/vnd.ms-lrm\":[\"lrm\"],\"application/vnd.ms-officetheme\":[\"thmx\"],\"application/vnd.ms-outlook\":[\"msg\"],\"application/vnd.ms-pki.seccat\":[\"cat\"],\"application/vnd.ms-pki.stl\":[\"*stl\"],\"application/vnd.ms-powerpoint\":[\"ppt\",\"pps\",\"pot\"],\"application/vnd.ms-powerpoint.addin.macroenabled.12\":[\"ppam\"],\"application/vnd.ms-powerpoint.presentation.macroenabled.12\":[\"pptm\"],\"application/vnd.ms-powerpoint.slide.macroenabled.12\":[\"sldm\"],\"application/vnd.ms-powerpoint.slideshow.macroenabled.12\":[\"ppsm\"],\"application/vnd.ms-powerpoint.template.macroenabled.12\":[\"potm\"],\"application/vnd.ms-project\":[\"mpp\",\"mpt\"],\"application/vnd.ms-word.document.macroenabled.12\":[\"docm\"],\"application/vnd.ms-word.template.macroenabled.12\":[\"dotm\"],\"application/vnd.ms-works\":[\"wps\",\"wks\",\"wcm\",\"wdb\"],\"application/vnd.ms-wpl\":[\"wpl\"],\"application/vnd.ms-xpsdocument\":[\"xps\"],\"application/vnd.mseq\":[\"mseq\"],\"application/vnd.musician\":[\"mus\"],\"application/vnd.muvee.style\":[\"msty\"],\"application/vnd.mynfc\":[\"taglet\"],\"application/vnd.neurolanguage.nlu\":[\"nlu\"],\"application/vnd.nitf\":[\"ntf\",\"nitf\"],\"application/vnd.noblenet-directory\":[\"nnd\"],\"application/vnd.noblenet-sealer\":[\"nns\"],\"application/vnd.noblenet-web\":[\"nnw\"],\"application/vnd.nokia.n-gage.ac+xml\":[\"*ac\"],\"application/vnd.nokia.n-gage.data\":[\"ngdat\"],\"application/vnd.nokia.n-gage.symbian.install\":[\"n-gage\"],\"application/vnd.nokia.radio-preset\":[\"rpst\"],\"application/vnd.nokia.radio-presets\":[\"rpss\"],\"application/vnd.novadigm.edm\":[\"edm\"],\"application/vnd.novadigm.edx\":[\"edx\"],\"application/vnd.novadigm.ext\":[\"ext\"],\"application/vnd.oasis.opendocument.chart\":[\"odc\"],\"application/vnd.oasis.opendocument.chart-template\":[\"otc\"],\"application/vnd.oasis.opendocument.database\":[\"odb\"],\"application/vnd.oasis.opendocument.formula\":[\"odf\"],\"application/vnd.oasis.opendocument.formula-template\":[\"odft\"],\"application/vnd.oasis.opendocument.graphics\":[\"odg\"],\"application/vnd.oasis.opendocument.graphics-template\":[\"otg\"],\"application/vnd.oasis.opendocument.image\":[\"odi\"],\"application/vnd.oasis.opendocument.image-template\":[\"oti\"],\"application/vnd.oasis.opendocument.presentation\":[\"odp\"],\"application/vnd.oasis.opendocument.presentation-template\":[\"otp\"],\"application/vnd.oasis.opendocument.spreadsheet\":[\"ods\"],\"application/vnd.oasis.opendocument.spreadsheet-template\":[\"ots\"],\"application/vnd.oasis.opendocument.text\":[\"odt\"],\"application/vnd.oasis.opendocument.text-master\":[\"odm\"],\"application/vnd.oasis.opendocument.text-template\":[\"ott\"],\"application/vnd.oasis.opendocument.text-web\":[\"oth\"],\"application/vnd.olpc-sugar\":[\"xo\"],\"application/vnd.oma.dd2+xml\":[\"dd2\"],\"application/vnd.openblox.game+xml\":[\"obgx\"],\"application/vnd.openofficeorg.extension\":[\"oxt\"],\"application/vnd.openstreetmap.data+xml\":[\"osm\"],\"application/vnd.openxmlformats-officedocument.presentationml.presentation\":[\"pptx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slide\":[\"sldx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\":[\"ppsx\"],\"application/vnd.openxmlformats-officedocument.presentationml.template\":[\"potx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":[\"xlsx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\":[\"xltx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":[\"docx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\":[\"dotx\"],\"application/vnd.osgeo.mapguide.package\":[\"mgp\"],\"application/vnd.osgi.dp\":[\"dp\"],\"application/vnd.osgi.subsystem\":[\"esa\"],\"application/vnd.palm\":[\"pdb\",\"pqa\",\"oprc\"],\"application/vnd.pawaafile\":[\"paw\"],\"application/vnd.pg.format\":[\"str\"],\"application/vnd.pg.osasli\":[\"ei6\"],\"application/vnd.picsel\":[\"efif\"],\"application/vnd.pmi.widget\":[\"wg\"],\"application/vnd.pocketlearn\":[\"plf\"],\"application/vnd.powerbuilder6\":[\"pbd\"],\"application/vnd.previewsystems.box\":[\"box\"],\"application/vnd.proteus.magazine\":[\"mgz\"],\"application/vnd.publishare-delta-tree\":[\"qps\"],\"application/vnd.pvi.ptid1\":[\"ptid\"],\"application/vnd.quark.quarkxpress\":[\"qxd\",\"qxt\",\"qwd\",\"qwt\",\"qxl\",\"qxb\"],\"application/vnd.rar\":[\"rar\"],\"application/vnd.realvnc.bed\":[\"bed\"],\"application/vnd.recordare.musicxml\":[\"mxl\"],\"application/vnd.recordare.musicxml+xml\":[\"musicxml\"],\"application/vnd.rig.cryptonote\":[\"cryptonote\"],\"application/vnd.rim.cod\":[\"cod\"],\"application/vnd.rn-realmedia\":[\"rm\"],\"application/vnd.rn-realmedia-vbr\":[\"rmvb\"],\"application/vnd.route66.link66+xml\":[\"link66\"],\"application/vnd.sailingtracker.track\":[\"st\"],\"application/vnd.seemail\":[\"see\"],\"application/vnd.sema\":[\"sema\"],\"application/vnd.semd\":[\"semd\"],\"application/vnd.semf\":[\"semf\"],\"application/vnd.shana.informed.formdata\":[\"ifm\"],\"application/vnd.shana.informed.formtemplate\":[\"itp\"],\"application/vnd.shana.informed.interchange\":[\"iif\"],\"application/vnd.shana.informed.package\":[\"ipk\"],\"application/vnd.simtech-mindmapper\":[\"twd\",\"twds\"],\"application/vnd.smaf\":[\"mmf\"],\"application/vnd.smart.teacher\":[\"teacher\"],\"application/vnd.software602.filler.form+xml\":[\"fo\"],\"application/vnd.solent.sdkm+xml\":[\"sdkm\",\"sdkd\"],\"application/vnd.spotfire.dxp\":[\"dxp\"],\"application/vnd.spotfire.sfs\":[\"sfs\"],\"application/vnd.stardivision.calc\":[\"sdc\"],\"application/vnd.stardivision.draw\":[\"sda\"],\"application/vnd.stardivision.impress\":[\"sdd\"],\"application/vnd.stardivision.math\":[\"smf\"],\"application/vnd.stardivision.writer\":[\"sdw\",\"vor\"],\"application/vnd.stardivision.writer-global\":[\"sgl\"],\"application/vnd.stepmania.package\":[\"smzip\"],\"application/vnd.stepmania.stepchart\":[\"sm\"],\"application/vnd.sun.wadl+xml\":[\"wadl\"],\"application/vnd.sun.xml.calc\":[\"sxc\"],\"application/vnd.sun.xml.calc.template\":[\"stc\"],\"application/vnd.sun.xml.draw\":[\"sxd\"],\"application/vnd.sun.xml.draw.template\":[\"std\"],\"application/vnd.sun.xml.impress\":[\"sxi\"],\"application/vnd.sun.xml.impress.template\":[\"sti\"],\"application/vnd.sun.xml.math\":[\"sxm\"],\"application/vnd.sun.xml.writer\":[\"sxw\"],\"application/vnd.sun.xml.writer.global\":[\"sxg\"],\"application/vnd.sun.xml.writer.template\":[\"stw\"],\"application/vnd.sus-calendar\":[\"sus\",\"susp\"],\"application/vnd.svd\":[\"svd\"],\"application/vnd.symbian.install\":[\"sis\",\"sisx\"],\"application/vnd.syncml+xml\":[\"xsm\"],\"application/vnd.syncml.dm+wbxml\":[\"bdm\"],\"application/vnd.syncml.dm+xml\":[\"xdm\"],\"application/vnd.syncml.dmddf+xml\":[\"ddf\"],\"application/vnd.tao.intent-module-archive\":[\"tao\"],\"application/vnd.tcpdump.pcap\":[\"pcap\",\"cap\",\"dmp\"],\"application/vnd.tmobile-livetv\":[\"tmo\"],\"application/vnd.trid.tpt\":[\"tpt\"],\"application/vnd.triscape.mxs\":[\"mxs\"],\"application/vnd.trueapp\":[\"tra\"],\"application/vnd.ufdl\":[\"ufd\",\"ufdl\"],\"application/vnd.uiq.theme\":[\"utz\"],\"application/vnd.umajin\":[\"umj\"],\"application/vnd.unity\":[\"unityweb\"],\"application/vnd.uoml+xml\":[\"uoml\"],\"application/vnd.vcx\":[\"vcx\"],\"application/vnd.visio\":[\"vsd\",\"vst\",\"vss\",\"vsw\"],\"application/vnd.visionary\":[\"vis\"],\"application/vnd.vsf\":[\"vsf\"],\"application/vnd.wap.wbxml\":[\"wbxml\"],\"application/vnd.wap.wmlc\":[\"wmlc\"],\"application/vnd.wap.wmlscriptc\":[\"wmlsc\"],\"application/vnd.webturbo\":[\"wtb\"],\"application/vnd.wolfram.player\":[\"nbp\"],\"application/vnd.wordperfect\":[\"wpd\"],\"application/vnd.wqd\":[\"wqd\"],\"application/vnd.wt.stf\":[\"stf\"],\"application/vnd.xara\":[\"xar\"],\"application/vnd.xfdl\":[\"xfdl\"],\"application/vnd.yamaha.hv-dic\":[\"hvd\"],\"application/vnd.yamaha.hv-script\":[\"hvs\"],\"application/vnd.yamaha.hv-voice\":[\"hvp\"],\"application/vnd.yamaha.openscoreformat\":[\"osf\"],\"application/vnd.yamaha.openscoreformat.osfpvg+xml\":[\"osfpvg\"],\"application/vnd.yamaha.smaf-audio\":[\"saf\"],\"application/vnd.yamaha.smaf-phrase\":[\"spf\"],\"application/vnd.yellowriver-custom-menu\":[\"cmp\"],\"application/vnd.zul\":[\"zir\",\"zirz\"],\"application/vnd.zzazz.deck+xml\":[\"zaz\"],\"application/x-7z-compressed\":[\"7z\"],\"application/x-abiword\":[\"abw\"],\"application/x-ace-compressed\":[\"ace\"],\"application/x-apple-diskimage\":[\"*dmg\"],\"application/x-arj\":[\"arj\"],\"application/x-authorware-bin\":[\"aab\",\"x32\",\"u32\",\"vox\"],\"application/x-authorware-map\":[\"aam\"],\"application/x-authorware-seg\":[\"aas\"],\"application/x-bcpio\":[\"bcpio\"],\"application/x-bdoc\":[\"*bdoc\"],\"application/x-bittorrent\":[\"torrent\"],\"application/x-blorb\":[\"blb\",\"blorb\"],\"application/x-bzip\":[\"bz\"],\"application/x-bzip2\":[\"bz2\",\"boz\"],\"application/x-cbr\":[\"cbr\",\"cba\",\"cbt\",\"cbz\",\"cb7\"],\"application/x-cdlink\":[\"vcd\"],\"application/x-cfs-compressed\":[\"cfs\"],\"application/x-chat\":[\"chat\"],\"application/x-chess-pgn\":[\"pgn\"],\"application/x-chrome-extension\":[\"crx\"],\"application/x-cocoa\":[\"cco\"],\"application/x-conference\":[\"nsc\"],\"application/x-cpio\":[\"cpio\"],\"application/x-csh\":[\"csh\"],\"application/x-debian-package\":[\"*deb\",\"udeb\"],\"application/x-dgc-compressed\":[\"dgc\"],\"application/x-director\":[\"dir\",\"dcr\",\"dxr\",\"cst\",\"cct\",\"cxt\",\"w3d\",\"fgd\",\"swa\"],\"application/x-doom\":[\"wad\"],\"application/x-dtbncx+xml\":[\"ncx\"],\"application/x-dtbook+xml\":[\"dtb\"],\"application/x-dtbresource+xml\":[\"res\"],\"application/x-dvi\":[\"dvi\"],\"application/x-envoy\":[\"evy\"],\"application/x-eva\":[\"eva\"],\"application/x-font-bdf\":[\"bdf\"],\"application/x-font-ghostscript\":[\"gsf\"],\"application/x-font-linux-psf\":[\"psf\"],\"application/x-font-pcf\":[\"pcf\"],\"application/x-font-snf\":[\"snf\"],\"application/x-font-type1\":[\"pfa\",\"pfb\",\"pfm\",\"afm\"],\"application/x-freearc\":[\"arc\"],\"application/x-futuresplash\":[\"spl\"],\"application/x-gca-compressed\":[\"gca\"],\"application/x-glulx\":[\"ulx\"],\"application/x-gnumeric\":[\"gnumeric\"],\"application/x-gramps-xml\":[\"gramps\"],\"application/x-gtar\":[\"gtar\"],\"application/x-hdf\":[\"hdf\"],\"application/x-httpd-php\":[\"php\"],\"application/x-install-instructions\":[\"install\"],\"application/x-iso9660-image\":[\"*iso\"],\"application/x-iwork-keynote-sffkey\":[\"*key\"],\"application/x-iwork-numbers-sffnumbers\":[\"*numbers\"],\"application/x-iwork-pages-sffpages\":[\"*pages\"],\"application/x-java-archive-diff\":[\"jardiff\"],\"application/x-java-jnlp-file\":[\"jnlp\"],\"application/x-keepass2\":[\"kdbx\"],\"application/x-latex\":[\"latex\"],\"application/x-lua-bytecode\":[\"luac\"],\"application/x-lzh-compressed\":[\"lzh\",\"lha\"],\"application/x-makeself\":[\"run\"],\"application/x-mie\":[\"mie\"],\"application/x-mobipocket-ebook\":[\"prc\",\"mobi\"],\"application/x-ms-application\":[\"application\"],\"application/x-ms-shortcut\":[\"lnk\"],\"application/x-ms-wmd\":[\"wmd\"],\"application/x-ms-wmz\":[\"wmz\"],\"application/x-ms-xbap\":[\"xbap\"],\"application/x-msaccess\":[\"mdb\"],\"application/x-msbinder\":[\"obd\"],\"application/x-mscardfile\":[\"crd\"],\"application/x-msclip\":[\"clp\"],\"application/x-msdos-program\":[\"*exe\"],\"application/x-msdownload\":[\"*exe\",\"*dll\",\"com\",\"bat\",\"*msi\"],\"application/x-msmediaview\":[\"mvb\",\"m13\",\"m14\"],\"application/x-msmetafile\":[\"*wmf\",\"*wmz\",\"*emf\",\"emz\"],\"application/x-msmoney\":[\"mny\"],\"application/x-mspublisher\":[\"pub\"],\"application/x-msschedule\":[\"scd\"],\"application/x-msterminal\":[\"trm\"],\"application/x-mswrite\":[\"wri\"],\"application/x-netcdf\":[\"nc\",\"cdf\"],\"application/x-ns-proxy-autoconfig\":[\"pac\"],\"application/x-nzb\":[\"nzb\"],\"application/x-perl\":[\"pl\",\"pm\"],\"application/x-pilot\":[\"*prc\",\"*pdb\"],\"application/x-pkcs12\":[\"p12\",\"pfx\"],\"application/x-pkcs7-certificates\":[\"p7b\",\"spc\"],\"application/x-pkcs7-certreqresp\":[\"p7r\"],\"application/x-rar-compressed\":[\"*rar\"],\"application/x-redhat-package-manager\":[\"rpm\"],\"application/x-research-info-systems\":[\"ris\"],\"application/x-sea\":[\"sea\"],\"application/x-sh\":[\"sh\"],\"application/x-shar\":[\"shar\"],\"application/x-shockwave-flash\":[\"swf\"],\"application/x-silverlight-app\":[\"xap\"],\"application/x-sql\":[\"sql\"],\"application/x-stuffit\":[\"sit\"],\"application/x-stuffitx\":[\"sitx\"],\"application/x-subrip\":[\"srt\"],\"application/x-sv4cpio\":[\"sv4cpio\"],\"application/x-sv4crc\":[\"sv4crc\"],\"application/x-t3vm-image\":[\"t3\"],\"application/x-tads\":[\"gam\"],\"application/x-tar\":[\"tar\"],\"application/x-tcl\":[\"tcl\",\"tk\"],\"application/x-tex\":[\"tex\"],\"application/x-tex-tfm\":[\"tfm\"],\"application/x-texinfo\":[\"texinfo\",\"texi\"],\"application/x-tgif\":[\"*obj\"],\"application/x-ustar\":[\"ustar\"],\"application/x-virtualbox-hdd\":[\"hdd\"],\"application/x-virtualbox-ova\":[\"ova\"],\"application/x-virtualbox-ovf\":[\"ovf\"],\"application/x-virtualbox-vbox\":[\"vbox\"],\"application/x-virtualbox-vbox-extpack\":[\"vbox-extpack\"],\"application/x-virtualbox-vdi\":[\"vdi\"],\"application/x-virtualbox-vhd\":[\"vhd\"],\"application/x-virtualbox-vmdk\":[\"vmdk\"],\"application/x-wais-source\":[\"src\"],\"application/x-web-app-manifest+json\":[\"webapp\"],\"application/x-x509-ca-cert\":[\"der\",\"crt\",\"pem\"],\"application/x-xfig\":[\"fig\"],\"application/x-xliff+xml\":[\"*xlf\"],\"application/x-xpinstall\":[\"xpi\"],\"application/x-xz\":[\"xz\"],\"application/x-zmachine\":[\"z1\",\"z2\",\"z3\",\"z4\",\"z5\",\"z6\",\"z7\",\"z8\"],\"audio/vnd.dece.audio\":[\"uva\",\"uvva\"],\"audio/vnd.digital-winds\":[\"eol\"],\"audio/vnd.dra\":[\"dra\"],\"audio/vnd.dts\":[\"dts\"],\"audio/vnd.dts.hd\":[\"dtshd\"],\"audio/vnd.lucent.voice\":[\"lvp\"],\"audio/vnd.ms-playready.media.pya\":[\"pya\"],\"audio/vnd.nuera.ecelp4800\":[\"ecelp4800\"],\"audio/vnd.nuera.ecelp7470\":[\"ecelp7470\"],\"audio/vnd.nuera.ecelp9600\":[\"ecelp9600\"],\"audio/vnd.rip\":[\"rip\"],\"audio/x-aac\":[\"aac\"],\"audio/x-aiff\":[\"aif\",\"aiff\",\"aifc\"],\"audio/x-caf\":[\"caf\"],\"audio/x-flac\":[\"flac\"],\"audio/x-m4a\":[\"*m4a\"],\"audio/x-matroska\":[\"mka\"],\"audio/x-mpegurl\":[\"m3u\"],\"audio/x-ms-wax\":[\"wax\"],\"audio/x-ms-wma\":[\"wma\"],\"audio/x-pn-realaudio\":[\"ram\",\"ra\"],\"audio/x-pn-realaudio-plugin\":[\"rmp\"],\"audio/x-realaudio\":[\"*ra\"],\"audio/x-wav\":[\"*wav\"],\"chemical/x-cdx\":[\"cdx\"],\"chemical/x-cif\":[\"cif\"],\"chemical/x-cmdf\":[\"cmdf\"],\"chemical/x-cml\":[\"cml\"],\"chemical/x-csml\":[\"csml\"],\"chemical/x-xyz\":[\"xyz\"],\"image/prs.btif\":[\"btif\"],\"image/prs.pti\":[\"pti\"],\"image/vnd.adobe.photoshop\":[\"psd\"],\"image/vnd.airzip.accelerator.azv\":[\"azv\"],\"image/vnd.dece.graphic\":[\"uvi\",\"uvvi\",\"uvg\",\"uvvg\"],\"image/vnd.djvu\":[\"djvu\",\"djv\"],\"image/vnd.dvb.subtitle\":[\"*sub\"],\"image/vnd.dwg\":[\"dwg\"],\"image/vnd.dxf\":[\"dxf\"],\"image/vnd.fastbidsheet\":[\"fbs\"],\"image/vnd.fpx\":[\"fpx\"],\"image/vnd.fst\":[\"fst\"],\"image/vnd.fujixerox.edmics-mmr\":[\"mmr\"],\"image/vnd.fujixerox.edmics-rlc\":[\"rlc\"],\"image/vnd.microsoft.icon\":[\"ico\"],\"image/vnd.ms-dds\":[\"dds\"],\"image/vnd.ms-modi\":[\"mdi\"],\"image/vnd.ms-photo\":[\"wdp\"],\"image/vnd.net-fpx\":[\"npx\"],\"image/vnd.pco.b16\":[\"b16\"],\"image/vnd.tencent.tap\":[\"tap\"],\"image/vnd.valve.source.texture\":[\"vtf\"],\"image/vnd.wap.wbmp\":[\"wbmp\"],\"image/vnd.xiff\":[\"xif\"],\"image/vnd.zbrush.pcx\":[\"pcx\"],\"image/x-3ds\":[\"3ds\"],\"image/x-cmu-raster\":[\"ras\"],\"image/x-cmx\":[\"cmx\"],\"image/x-freehand\":[\"fh\",\"fhc\",\"fh4\",\"fh5\",\"fh7\"],\"image/x-icon\":[\"*ico\"],\"image/x-jng\":[\"jng\"],\"image/x-mrsid-image\":[\"sid\"],\"image/x-ms-bmp\":[\"*bmp\"],\"image/x-pcx\":[\"*pcx\"],\"image/x-pict\":[\"pic\",\"pct\"],\"image/x-portable-anymap\":[\"pnm\"],\"image/x-portable-bitmap\":[\"pbm\"],\"image/x-portable-graymap\":[\"pgm\"],\"image/x-portable-pixmap\":[\"ppm\"],\"image/x-rgb\":[\"rgb\"],\"image/x-tga\":[\"tga\"],\"image/x-xbitmap\":[\"xbm\"],\"image/x-xpixmap\":[\"xpm\"],\"image/x-xwindowdump\":[\"xwd\"],\"message/vnd.wfa.wsc\":[\"wsc\"],\"model/vnd.collada+xml\":[\"dae\"],\"model/vnd.dwf\":[\"dwf\"],\"model/vnd.gdl\":[\"gdl\"],\"model/vnd.gtw\":[\"gtw\"],\"model/vnd.mts\":[\"mts\"],\"model/vnd.opengex\":[\"ogex\"],\"model/vnd.parasolid.transmit.binary\":[\"x_b\"],\"model/vnd.parasolid.transmit.text\":[\"x_t\"],\"model/vnd.sap.vds\":[\"vds\"],\"model/vnd.usdz+zip\":[\"usdz\"],\"model/vnd.valve.source.compiled-map\":[\"bsp\"],\"model/vnd.vtu\":[\"vtu\"],\"text/prs.lines.tag\":[\"dsc\"],\"text/vnd.curl\":[\"curl\"],\"text/vnd.curl.dcurl\":[\"dcurl\"],\"text/vnd.curl.mcurl\":[\"mcurl\"],\"text/vnd.curl.scurl\":[\"scurl\"],\"text/vnd.dvb.subtitle\":[\"sub\"],\"text/vnd.fly\":[\"fly\"],\"text/vnd.fmi.flexstor\":[\"flx\"],\"text/vnd.graphviz\":[\"gv\"],\"text/vnd.in3d.3dml\":[\"3dml\"],\"text/vnd.in3d.spot\":[\"spot\"],\"text/vnd.sun.j2me.app-descriptor\":[\"jad\"],\"text/vnd.wap.wml\":[\"wml\"],\"text/vnd.wap.wmlscript\":[\"wmls\"],\"text/x-asm\":[\"s\",\"asm\"],\"text/x-c\":[\"c\",\"cc\",\"cxx\",\"cpp\",\"h\",\"hh\",\"dic\"],\"text/x-component\":[\"htc\"],\"text/x-fortran\":[\"f\",\"for\",\"f77\",\"f90\"],\"text/x-handlebars-template\":[\"hbs\"],\"text/x-java-source\":[\"java\"],\"text/x-lua\":[\"lua\"],\"text/x-markdown\":[\"mkd\"],\"text/x-nfo\":[\"nfo\"],\"text/x-opml\":[\"opml\"],\"text/x-org\":[\"*org\"],\"text/x-pascal\":[\"p\",\"pas\"],\"text/x-processing\":[\"pde\"],\"text/x-sass\":[\"sass\"],\"text/x-scss\":[\"scss\"],\"text/x-setext\":[\"etx\"],\"text/x-sfv\":[\"sfv\"],\"text/x-suse-ymp\":[\"ymp\"],\"text/x-uuencode\":[\"uu\"],\"text/x-vcalendar\":[\"vcs\"],\"text/x-vcard\":[\"vcf\"],\"video/vnd.dece.hd\":[\"uvh\",\"uvvh\"],\"video/vnd.dece.mobile\":[\"uvm\",\"uvvm\"],\"video/vnd.dece.pd\":[\"uvp\",\"uvvp\"],\"video/vnd.dece.sd\":[\"uvs\",\"uvvs\"],\"video/vnd.dece.video\":[\"uvv\",\"uvvv\"],\"video/vnd.dvb.file\":[\"dvb\"],\"video/vnd.fvt\":[\"fvt\"],\"video/vnd.mpegurl\":[\"mxu\",\"m4u\"],\"video/vnd.ms-playready.media.pyv\":[\"pyv\"],\"video/vnd.uvvu.mp4\":[\"uvu\",\"uvvu\"],\"video/vnd.vivo\":[\"viv\"],\"video/x-f4v\":[\"f4v\"],\"video/x-fli\":[\"fli\"],\"video/x-flv\":[\"flv\"],\"video/x-m4v\":[\"m4v\"],\"video/x-matroska\":[\"mkv\",\"mk3d\",\"mks\"],\"video/x-mng\":[\"mng\"],\"video/x-ms-asf\":[\"asf\",\"asx\"],\"video/x-ms-vob\":[\"vob\"],\"video/x-ms-wm\":[\"wm\"],\"video/x-ms-wmv\":[\"wmv\"],\"video/x-ms-wmx\":[\"wmx\"],\"video/x-ms-wvx\":[\"wvx\"],\"video/x-msvideo\":[\"avi\"],\"video/x-sgi-movie\":[\"movie\"],\"video/x-smv\":[\"smv\"],\"x-conference/x-cooltalk\":[\"ice\"]};","module.exports = {\"application/andrew-inset\":[\"ez\"],\"application/applixware\":[\"aw\"],\"application/atom+xml\":[\"atom\"],\"application/atomcat+xml\":[\"atomcat\"],\"application/atomdeleted+xml\":[\"atomdeleted\"],\"application/atomsvc+xml\":[\"atomsvc\"],\"application/atsc-dwd+xml\":[\"dwd\"],\"application/atsc-held+xml\":[\"held\"],\"application/atsc-rsat+xml\":[\"rsat\"],\"application/bdoc\":[\"bdoc\"],\"application/calendar+xml\":[\"xcs\"],\"application/ccxml+xml\":[\"ccxml\"],\"application/cdfx+xml\":[\"cdfx\"],\"application/cdmi-capability\":[\"cdmia\"],\"application/cdmi-container\":[\"cdmic\"],\"application/cdmi-domain\":[\"cdmid\"],\"application/cdmi-object\":[\"cdmio\"],\"application/cdmi-queue\":[\"cdmiq\"],\"application/cu-seeme\":[\"cu\"],\"application/dash+xml\":[\"mpd\"],\"application/davmount+xml\":[\"davmount\"],\"application/docbook+xml\":[\"dbk\"],\"application/dssc+der\":[\"dssc\"],\"application/dssc+xml\":[\"xdssc\"],\"application/ecmascript\":[\"es\",\"ecma\"],\"application/emma+xml\":[\"emma\"],\"application/emotionml+xml\":[\"emotionml\"],\"application/epub+zip\":[\"epub\"],\"application/exi\":[\"exi\"],\"application/express\":[\"exp\"],\"application/fdt+xml\":[\"fdt\"],\"application/font-tdpfr\":[\"pfr\"],\"application/geo+json\":[\"geojson\"],\"application/gml+xml\":[\"gml\"],\"application/gpx+xml\":[\"gpx\"],\"application/gxf\":[\"gxf\"],\"application/gzip\":[\"gz\"],\"application/hjson\":[\"hjson\"],\"application/hyperstudio\":[\"stk\"],\"application/inkml+xml\":[\"ink\",\"inkml\"],\"application/ipfix\":[\"ipfix\"],\"application/its+xml\":[\"its\"],\"application/java-archive\":[\"jar\",\"war\",\"ear\"],\"application/java-serialized-object\":[\"ser\"],\"application/java-vm\":[\"class\"],\"application/javascript\":[\"js\",\"mjs\"],\"application/json\":[\"json\",\"map\"],\"application/json5\":[\"json5\"],\"application/jsonml+json\":[\"jsonml\"],\"application/ld+json\":[\"jsonld\"],\"application/lgr+xml\":[\"lgr\"],\"application/lost+xml\":[\"lostxml\"],\"application/mac-binhex40\":[\"hqx\"],\"application/mac-compactpro\":[\"cpt\"],\"application/mads+xml\":[\"mads\"],\"application/manifest+json\":[\"webmanifest\"],\"application/marc\":[\"mrc\"],\"application/marcxml+xml\":[\"mrcx\"],\"application/mathematica\":[\"ma\",\"nb\",\"mb\"],\"application/mathml+xml\":[\"mathml\"],\"application/mbox\":[\"mbox\"],\"application/mediaservercontrol+xml\":[\"mscml\"],\"application/metalink+xml\":[\"metalink\"],\"application/metalink4+xml\":[\"meta4\"],\"application/mets+xml\":[\"mets\"],\"application/mmt-aei+xml\":[\"maei\"],\"application/mmt-usd+xml\":[\"musd\"],\"application/mods+xml\":[\"mods\"],\"application/mp21\":[\"m21\",\"mp21\"],\"application/mp4\":[\"mp4s\",\"m4p\"],\"application/msword\":[\"doc\",\"dot\"],\"application/mxf\":[\"mxf\"],\"application/n-quads\":[\"nq\"],\"application/n-triples\":[\"nt\"],\"application/node\":[\"cjs\"],\"application/octet-stream\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"],\"application/oda\":[\"oda\"],\"application/oebps-package+xml\":[\"opf\"],\"application/ogg\":[\"ogx\"],\"application/omdoc+xml\":[\"omdoc\"],\"application/onenote\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"],\"application/oxps\":[\"oxps\"],\"application/p2p-overlay+xml\":[\"relo\"],\"application/patch-ops-error+xml\":[\"xer\"],\"application/pdf\":[\"pdf\"],\"application/pgp-encrypted\":[\"pgp\"],\"application/pgp-signature\":[\"asc\",\"sig\"],\"application/pics-rules\":[\"prf\"],\"application/pkcs10\":[\"p10\"],\"application/pkcs7-mime\":[\"p7m\",\"p7c\"],\"application/pkcs7-signature\":[\"p7s\"],\"application/pkcs8\":[\"p8\"],\"application/pkix-attr-cert\":[\"ac\"],\"application/pkix-cert\":[\"cer\"],\"application/pkix-crl\":[\"crl\"],\"application/pkix-pkipath\":[\"pkipath\"],\"application/pkixcmp\":[\"pki\"],\"application/pls+xml\":[\"pls\"],\"application/postscript\":[\"ai\",\"eps\",\"ps\"],\"application/provenance+xml\":[\"provx\"],\"application/pskc+xml\":[\"pskcxml\"],\"application/raml+yaml\":[\"raml\"],\"application/rdf+xml\":[\"rdf\",\"owl\"],\"application/reginfo+xml\":[\"rif\"],\"application/relax-ng-compact-syntax\":[\"rnc\"],\"application/resource-lists+xml\":[\"rl\"],\"application/resource-lists-diff+xml\":[\"rld\"],\"application/rls-services+xml\":[\"rs\"],\"application/route-apd+xml\":[\"rapd\"],\"application/route-s-tsid+xml\":[\"sls\"],\"application/route-usd+xml\":[\"rusd\"],\"application/rpki-ghostbusters\":[\"gbr\"],\"application/rpki-manifest\":[\"mft\"],\"application/rpki-roa\":[\"roa\"],\"application/rsd+xml\":[\"rsd\"],\"application/rss+xml\":[\"rss\"],\"application/rtf\":[\"rtf\"],\"application/sbml+xml\":[\"sbml\"],\"application/scvp-cv-request\":[\"scq\"],\"application/scvp-cv-response\":[\"scs\"],\"application/scvp-vp-request\":[\"spq\"],\"application/scvp-vp-response\":[\"spp\"],\"application/sdp\":[\"sdp\"],\"application/senml+xml\":[\"senmlx\"],\"application/sensml+xml\":[\"sensmlx\"],\"application/set-payment-initiation\":[\"setpay\"],\"application/set-registration-initiation\":[\"setreg\"],\"application/shf+xml\":[\"shf\"],\"application/sieve\":[\"siv\",\"sieve\"],\"application/smil+xml\":[\"smi\",\"smil\"],\"application/sparql-query\":[\"rq\"],\"application/sparql-results+xml\":[\"srx\"],\"application/srgs\":[\"gram\"],\"application/srgs+xml\":[\"grxml\"],\"application/sru+xml\":[\"sru\"],\"application/ssdl+xml\":[\"ssdl\"],\"application/ssml+xml\":[\"ssml\"],\"application/swid+xml\":[\"swidtag\"],\"application/tei+xml\":[\"tei\",\"teicorpus\"],\"application/thraud+xml\":[\"tfi\"],\"application/timestamped-data\":[\"tsd\"],\"application/toml\":[\"toml\"],\"application/trig\":[\"trig\"],\"application/ttml+xml\":[\"ttml\"],\"application/ubjson\":[\"ubj\"],\"application/urc-ressheet+xml\":[\"rsheet\"],\"application/urc-targetdesc+xml\":[\"td\"],\"application/voicexml+xml\":[\"vxml\"],\"application/wasm\":[\"wasm\"],\"application/widget\":[\"wgt\"],\"application/winhlp\":[\"hlp\"],\"application/wsdl+xml\":[\"wsdl\"],\"application/wspolicy+xml\":[\"wspolicy\"],\"application/xaml+xml\":[\"xaml\"],\"application/xcap-att+xml\":[\"xav\"],\"application/xcap-caps+xml\":[\"xca\"],\"application/xcap-diff+xml\":[\"xdf\"],\"application/xcap-el+xml\":[\"xel\"],\"application/xcap-ns+xml\":[\"xns\"],\"application/xenc+xml\":[\"xenc\"],\"application/xhtml+xml\":[\"xhtml\",\"xht\"],\"application/xliff+xml\":[\"xlf\"],\"application/xml\":[\"xml\",\"xsl\",\"xsd\",\"rng\"],\"application/xml-dtd\":[\"dtd\"],\"application/xop+xml\":[\"xop\"],\"application/xproc+xml\":[\"xpl\"],\"application/xslt+xml\":[\"*xsl\",\"xslt\"],\"application/xspf+xml\":[\"xspf\"],\"application/xv+xml\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"],\"application/yang\":[\"yang\"],\"application/yin+xml\":[\"yin\"],\"application/zip\":[\"zip\"],\"audio/3gpp\":[\"*3gpp\"],\"audio/adpcm\":[\"adp\"],\"audio/amr\":[\"amr\"],\"audio/basic\":[\"au\",\"snd\"],\"audio/midi\":[\"mid\",\"midi\",\"kar\",\"rmi\"],\"audio/mobile-xmf\":[\"mxmf\"],\"audio/mp3\":[\"*mp3\"],\"audio/mp4\":[\"m4a\",\"mp4a\"],\"audio/mpeg\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"],\"audio/ogg\":[\"oga\",\"ogg\",\"spx\",\"opus\"],\"audio/s3m\":[\"s3m\"],\"audio/silk\":[\"sil\"],\"audio/wav\":[\"wav\"],\"audio/wave\":[\"*wav\"],\"audio/webm\":[\"weba\"],\"audio/xm\":[\"xm\"],\"font/collection\":[\"ttc\"],\"font/otf\":[\"otf\"],\"font/ttf\":[\"ttf\"],\"font/woff\":[\"woff\"],\"font/woff2\":[\"woff2\"],\"image/aces\":[\"exr\"],\"image/apng\":[\"apng\"],\"image/avif\":[\"avif\"],\"image/bmp\":[\"bmp\"],\"image/cgm\":[\"cgm\"],\"image/dicom-rle\":[\"drle\"],\"image/emf\":[\"emf\"],\"image/fits\":[\"fits\"],\"image/g3fax\":[\"g3\"],\"image/gif\":[\"gif\"],\"image/heic\":[\"heic\"],\"image/heic-sequence\":[\"heics\"],\"image/heif\":[\"heif\"],\"image/heif-sequence\":[\"heifs\"],\"image/hej2k\":[\"hej2\"],\"image/hsj2\":[\"hsj2\"],\"image/ief\":[\"ief\"],\"image/jls\":[\"jls\"],\"image/jp2\":[\"jp2\",\"jpg2\"],\"image/jpeg\":[\"jpeg\",\"jpg\",\"jpe\"],\"image/jph\":[\"jph\"],\"image/jphc\":[\"jhc\"],\"image/jpm\":[\"jpm\"],\"image/jpx\":[\"jpx\",\"jpf\"],\"image/jxr\":[\"jxr\"],\"image/jxra\":[\"jxra\"],\"image/jxrs\":[\"jxrs\"],\"image/jxs\":[\"jxs\"],\"image/jxsc\":[\"jxsc\"],\"image/jxsi\":[\"jxsi\"],\"image/jxss\":[\"jxss\"],\"image/ktx\":[\"ktx\"],\"image/ktx2\":[\"ktx2\"],\"image/png\":[\"png\"],\"image/sgi\":[\"sgi\"],\"image/svg+xml\":[\"svg\",\"svgz\"],\"image/t38\":[\"t38\"],\"image/tiff\":[\"tif\",\"tiff\"],\"image/tiff-fx\":[\"tfx\"],\"image/webp\":[\"webp\"],\"image/wmf\":[\"wmf\"],\"message/disposition-notification\":[\"disposition-notification\"],\"message/global\":[\"u8msg\"],\"message/global-delivery-status\":[\"u8dsn\"],\"message/global-disposition-notification\":[\"u8mdn\"],\"message/global-headers\":[\"u8hdr\"],\"message/rfc822\":[\"eml\",\"mime\"],\"model/3mf\":[\"3mf\"],\"model/gltf+json\":[\"gltf\"],\"model/gltf-binary\":[\"glb\"],\"model/iges\":[\"igs\",\"iges\"],\"model/mesh\":[\"msh\",\"mesh\",\"silo\"],\"model/mtl\":[\"mtl\"],\"model/obj\":[\"obj\"],\"model/step+xml\":[\"stpx\"],\"model/step+zip\":[\"stpz\"],\"model/step-xml+zip\":[\"stpxz\"],\"model/stl\":[\"stl\"],\"model/vrml\":[\"wrl\",\"vrml\"],\"model/x3d+binary\":[\"*x3db\",\"x3dbz\"],\"model/x3d+fastinfoset\":[\"x3db\"],\"model/x3d+vrml\":[\"*x3dv\",\"x3dvz\"],\"model/x3d+xml\":[\"x3d\",\"x3dz\"],\"model/x3d-vrml\":[\"x3dv\"],\"text/cache-manifest\":[\"appcache\",\"manifest\"],\"text/calendar\":[\"ics\",\"ifb\"],\"text/coffeescript\":[\"coffee\",\"litcoffee\"],\"text/css\":[\"css\"],\"text/csv\":[\"csv\"],\"text/html\":[\"html\",\"htm\",\"shtml\"],\"text/jade\":[\"jade\"],\"text/jsx\":[\"jsx\"],\"text/less\":[\"less\"],\"text/markdown\":[\"markdown\",\"md\"],\"text/mathml\":[\"mml\"],\"text/mdx\":[\"mdx\"],\"text/n3\":[\"n3\"],\"text/plain\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"],\"text/richtext\":[\"rtx\"],\"text/rtf\":[\"*rtf\"],\"text/sgml\":[\"sgml\",\"sgm\"],\"text/shex\":[\"shex\"],\"text/slim\":[\"slim\",\"slm\"],\"text/spdx\":[\"spdx\"],\"text/stylus\":[\"stylus\",\"styl\"],\"text/tab-separated-values\":[\"tsv\"],\"text/troff\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"],\"text/turtle\":[\"ttl\"],\"text/uri-list\":[\"uri\",\"uris\",\"urls\"],\"text/vcard\":[\"vcard\"],\"text/vtt\":[\"vtt\"],\"text/xml\":[\"*xml\"],\"text/yaml\":[\"yaml\",\"yml\"],\"video/3gpp\":[\"3gp\",\"3gpp\"],\"video/3gpp2\":[\"3g2\"],\"video/h261\":[\"h261\"],\"video/h263\":[\"h263\"],\"video/h264\":[\"h264\"],\"video/iso.segment\":[\"m4s\"],\"video/jpeg\":[\"jpgv\"],\"video/jpm\":[\"*jpm\",\"jpgm\"],\"video/mj2\":[\"mj2\",\"mjp2\"],\"video/mp2t\":[\"ts\"],\"video/mp4\":[\"mp4\",\"mp4v\",\"mpg4\"],\"video/mpeg\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"],\"video/ogg\":[\"ogv\"],\"video/quicktime\":[\"qt\",\"mov\"],\"video/webm\":[\"webm\"]};","// empty module for shims\nmodule.exports = {};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"thebe-lite:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t};\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","__webpack_require__.amdO = {};","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".thebe-lite.min.js\";\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t143: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkthebe_lite\"] = self[\"webpackChunkthebe_lite\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(1920);\n"],"names":["Object","defineProperty","exports","value","BaseManager","signaling_1","serverconnection_1","constructor","options","_a","this","_isDisposed","_disposed","Signal","serverSettings","ServerConnection","makeSettings","disposed","isDisposed","isActive","dispose","emit","undefined","clearData","BuildManager","coreutils_1","_url","baseUrl","appUrl","URLExt","join","isAvailable","PageConfig","getOption","toLowerCase","shouldCheck","getStatus","makeRequest","then","response","status","ResponseError","json","data","Error","message","build","method","cancel","ConfigWithDefaults","ConfigSection","__1","create","section","DefaultConfigSection","load","settings","encodeURIComponent","name","_data","async","newdata","init","body","JSON","stringify","_b","_className","_section","_defaults","defaults","className","get","key","_classData","set","d","d2","update","__createBinding","o","m","k","k2","desc","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__setModuleDefault","v","__importStar","mod","result","prototype","hasOwnProperty","call","Drive","ContentsManager","Contents","validate","Private","validateContentsModel","contents","validateCheckpointModel","checkpoint","_additionalDrives","Map","_fileChanged","_defaultDrive","defaultDrive","fileChanged","connect","_onFileChanged","addDrive","drive","getSharedModelFactory","path","_driveForPath","sharedModelFactory","localPath","parts","split","firstParts","length","has","PathExt","slice","removeSlash","normalize","resolvePath","root","driveName","resolved","resolve","contentsModel","listing","type","content","item","push","_toGlobalPath","serverPath","getDownloadUrl","newUntitled","globalPath","delete","rename","newPath","drive1","path1","drive2","path2","save","copy","fromFile","toDir","createCheckpoint","listCheckpoints","restoreCheckpoint","checkpointID","deleteCheckpoint","sender","args","newValue","oldValue","_c","_apiEndpoint","apiEndpoint","url","_getUrl","params","objectToQueryString","encodeParts","xsrfTokenMatch","document","cookie","match","fullUrl","URL","searchParams","append","toString","Promise","ext","normalizeExtension","oldLocalPath","newLocalPath","copy_from","Array","isArray","i","map","extension","indexOf","validate_1","model","validateProperty","EventManager","polling_1","SERVICE_EVENTS_URL","_socket","_poll","Poll","factory","_subscribe","_stream","Stream","start","stream","socket","onopen","onerror","onmessage","onclose","close","stop","event","token","_","reject","WebSocket","wsUrl","msg","parse","__exportStar","p","CommHandler","disposable_1","KernelMessage","DisposableDelegate","target","id","kernel","disposeCb","super","_target","_id","_kernel","commId","targetName","onClose","_onClose","cb","onMsg","_onMsg","open","metadata","buffers","createMessage","msgType","channel","username","session","clientId","comm_id","target_name","sendShellMessage","send","disposeOnDone","future","KernelConnection","coreutils_2","comm_1","future_1","serialize_1","kernelspec_1","restapi","RESTARTING_KERNEL_SESSION","_d","_createSocket","useProtocols","_errorIfDisposed","_clearSocket","_updateConnectionStatus","partialUrl","KERNEL_SERVICE_URL","display","replace","console","debug","_clientId","appendToken","supportedProtocols","_supportedProtocols","_ws","binaryType","alreadyCalledOnclose","getKernelModel","evt","_reason","_model","execution_state","_updateStatus","_onWSClose","err","NetworkError","timeout","getRandomIntInclusive","setTimeout","earlyClose","_onWSMessage","_onWSOpen","protocol","includes","log","_selectedProtocol","deserialize","validateMessage","error","_kernelSession","header","_msgChain","_handleMessage","catch","startsWith","_anyMessage","direction","_reconnect","_name","_status","_connectionStatus","_username","_reconnectLimit","_reconnectAttempt","_reconnectTimeout","values","supportedKernelWebSocketProtocols","_futures","_comms","_targetRegistry","_info","PromiseDelegate","_pendingMessages","_statusChanged","_connectionStatusChanged","_iopubMessage","_pendingInput","_unhandledMessage","_displayIdToParentIds","_msgIdToDisplayIds","_hasPendingInput","_noOp","UUID","uuid4","handleComms","statusChanged","connectionStatusChanged","iopubMessage","unhandledMessage","reason","anyMessage","pendingInput","connectionStatus","info","promise","spec","_specPromise","KernelSpecAPI","getSpecs","specs","kernelspecs","clone","_clearKernelState","expectReply","_sendKernelShellControl","KernelShellFutureHandler","sendControlMessage","KernelControlFutureHandler","ctor","_sendMessage","msgId","msg_id","displayIds","forEach","displayId","msgIds","idx","splice","queue","isInfoRequestMsg","serialize","hasPendingInput","interruptKernel","restartKernel","reconnect","fulfill","disconnect","shutdownKernel","handleShutdown","reply","handleShellMessage","e","requestComplete","requestInspect","requestHistory","requestExecute","silent","store_history","user_expressions","allow_stdin","stop_on_error","requestDebug","requestIsComplete","requestCommInfo","sendInputReply","parent_header","createComm","comm","_unregisterComm","hasComm","registerCommTarget","callback","removeCommTarget","registerMessageHook","hook","removeMessageHook","removeInputGuard","parentIds","updateMsg","JSONExt","deepCopy","msg_type","all","parentId","handleMsg","logKernelStatus","_sendPending","shift","clear","_assertCurrentMessage","loadObject","target_module","clearTimeout","restarting","requestKernelInfo","sendPendingCalled","sendPendingOnce","timeoutHandle","handled","isDisplayDataMsg","isUpdateDisplayDataMsg","isExecuteResultMsg","transient","_handleDisplayId","parentHeader","owned","executionState","_handleCommOpen","_handleCommMsg","_handleCommClose","Math","pow","warn","floor","done","moduleName","registry","requirejs","min","max","ceil","random","KernelFutureHandler","_stdin","noOp","_iopub","_reply","_done","_hooks","HookList","_disposeOnDone","_msg","_setFlag","KernelFutureFlag","GotReply","onReply","onIOPub","onStdin","add","remove","_testFlag","IsDone","_handleReply","_handleStdin","_handleIOPub","_replyMsg","GotIdle","_handleDone","stdin","process","iopub","isStatusMsg","flag","defer","requestAnimationFrame","setImmediate","index","_scheduleCompact","_processing","processing","continueHandling","_compactScheduled","_compact","numNulls","len","KernelAPI","Kernel","default_1","KernelManager","basemanager_1","restapi_1","_isReady","_kernelConnections","Set","_models","_runningChanged","_connectionFailure","_pollModels","auto","requestRunning","frequency","interval","backoff","standby","_ready","tick","isReady","ready","runningChanged","connectionFailure","x","connectTo","kc","kernelConnection","_onStarted","refreshRunning","running","refresh","createOptions","connectOptions","startNew","keys","models","listRunning","size","every","existing","connections","last_activity","traceback","_onStatusChanged","_onDisposed","NoopManager","arguments","_readyPromise","parentReady","isInputReplyMsg","isInputRequestMsg","isDebugReplyMsg","isDebugRequestMsg","isExecuteReplyMsg","isCommMsgMsg","isCommCloseMsg","isCommOpenMsg","isDebugEventMsg","isClearOutputMsg","isErrorMsg","isExecuteInputMsg","isStreamMsg","_e","date","Date","toISOString","version","validateModels","validateModel","v1KernelWebsocketJupyterOrg","serializeV1KernelWebsocketJupyterOrg","serializeDefault","deserializeV1KernelWebsocketJupyterOrg","deserializeDefault","binMsg","DataView","offsetNumber","Number","getBigUint64","offsets","decoder","TextDecoder","decode","encoder","TextEncoder","channelEncoded","encode","headerEncoded","parentHeaderEncoded","metadataEncoded","contentEncoded","binMsgNoBuff","Uint8Array","buffersByteLength","buffer","byteLength","word","ArrayBuffer","setBigUint64","BigInt","isView","buf","nbufs","getUint32","jsonBytes","deserializeBinary","origBuffers","jsonUtf8","b","msgBuf","view","setUint32","serializeBinary","HEADER_FIELDS","IOPUB_CONTENT_FIELDS","text","display_data","execute_input","code","execution_count","execute_result","ename","evalue","clear_output","wait","comm_open","comm_msg","comm_close","shutdown_reply","restart","validateHeader","fields","names","validateIOPubContent","KernelSpec","KernelSpecManager","_specs","_specsChanged","requestSpecs","_pollSpecs","specsChanged","deepEqual","validateSpecModels","validateSpecModel","env","resources","language","display_name","argv","defaultSpec","default","ks","ServiceManager","builder_1","contents_1","event_1","kernel_1","nbconvert_1","session_1","setting_1","terminal_1","user_1","workspace_1","normalized","events","kernels","sessions","SessionManager","kernelManager","SettingManager","terminals","TerminalManager","builder","workspaces","WorkspaceManager","nbconvert","NbConvertManager","user","UserManager","_onConnectionFailure","readyList","_exportFormats","_requestingFormats","base","exportList","mimeType","output_mimetype","force","fetchExportFormats","WEBSOCKET","window","handleRequest","static","_defaultMessage","statusText","TypeError","original","stack","pageBaseUrl","getBaseUrl","pageWsUrl","getWsUrl","cache","credentials","fetch","Headers","Request","getToken","JEST_WORKER_ID","getHostName","test","getTime","request","authenticated","headers","xsrfToken","matches","getCookie","SessionConnection","_path","_type","_kernelChanged","_propertyChanged","_connectToKernel","connectToKernel","_kernelConnectionOptions","kernelConnectionOptions","setupKernel","kernelChanged","propertyChanged","oldModel","_handleModelChange","_patch","shutdownSession","onKernelStatus","onKernelConnectionStatus","onPendingInput","onUnhandledMessage","onIOPubMessage","onAnyMessage","state","updateSession","SessionAPI","Session","_sessionConnections","_kernelManager","sessionConnection","startSession","filter","shutdown","sc","_onChanged","getSessionModel","getSessionUrl","SESSION_SERVICE_URL","updateLegacySessionModel","validate_2","notebook","statedb_1","DataConnector","query","ids","plugin","composite","raw","idsOnly","idsOnlyParam","ids_only","TerminalConnection","_messageReceived","messageReceived","shutdownTerminal","getTermUrl","TERMINAL_SERVICE_URL","TerminalAPI","Terminal","_names","_terminalConnections","terminalConnection","Symbol","iterator","cwd","sort","tc","String","errorIfNotAvailable","SERVICE_ID","_userChanged","requestUser","identity","_identity","permissions","_permissions","userChanged","oldUser","newUser","localStorage","getItem","initials","color","localUser","substring","getRandomColor","setItem","userColors","object","typeName","valid","findIndex","workspace","ActivityMonitor","_timer","_timeout","_activityStopped","signal","_onSignalFired","activityStopped","_sender","_args","MarkdownCodeBlocks","CODE_BLOCK_MARKER","markdownExtensions","MarkdownCodeBlock","startLine","endLine","isMarkdown","findMarkdownCodeBlocks","lines","codeBlocks","currentBlock","lineIndex","line","lineContainsMarker","constructingBlock","firstIndex","lastIndex","lastIndexOf","__importDefault","minimist_1","url_1","configData","getBodyData","found","el","getElementById","textContent","cli","fullPath","eval","isObject","setOption","last","getTreeUrl","getShareUrl","getTreeShareUrl","getUrl","toShare","mode","labOrDoc","defaultWorkspace","treePath","getNBConvertURL","format","download","notebookPath","getNotebookVersion","notebookVersion","Extension","val","dataset","decodeURIComponent","populate","deferred","disabled","isDeferred","separatorIndex","extName","some","isDisabled","path_1","paths","posix","basename","dirname","dir","extname","relative","from","to","signalToPromise","waitForSignal","cleanup","slot","Text","HAS_SURROGATES","jsIndexToCharIndex","jsIdx","charIdx","charCode","charCodeAt","nextCharCode","charIndexToJsIndex","camelCase","str","upper","p1","p2","toUpperCase","titleCase","charAt","Time","UNITS","milliseconds","formatHuman","lang","documentElement","formatter","Intl","RelativeTimeFormat","numeric","delta","now","unit","amount","DateTimeFormat","dateStyle","timeStyle","url_parse_1","a","createElement","href","u","isSchemaLess","slashes","prefix","auth","host","pathname","hostname","queryStringToObject","reduce","acc","isLocal","RestorablePool","properties_1","_added","_current","_currentChanged","_hasRestored","_objects","_restore","_restored","_updated","namespace","added","current","obj","currentChanged","restored","updated","warning","_onInstanceDisposed","injectedProperty","connector","objName","nameProperty","find","fn","filtered","inject","command","when","promises","list","concat","saved","execute","injected","oldName","newName","AttachedProperty","StateDB","_changed","transform","_connector","Connector","transformation","_clear","_merge","_overwrite","changed","_fetch","_list","_remove","_save","_storage","IStateDB","Token","isPrimitive","first","second","a1","a2","n","deepArrayEqual","firstValue","secondValue","deepObjectEqual","deepArrayCopy","subvalue","deepObjectCopy","emptyObject","freeze","emptyArray","fallbackRandomValues","Random","getRandomValues","crypto","msCrypto","bytes","lut","uuid4Factory","MimeData","_types","_values","types","hasData","mime","getData","setData","_resolve","_reject","description","_tokenStructuralPropertyT","_fn","ObservableDisposableDelegate","DisposableSet","_items","contains","items","ObservableDisposableSet","_lingered","_tick","_ticked","_factory","_linger","linger","DEFAULT_LINGER","_standby","DEFAULT_STANDBY","_state","DEFAULT_STATE","timestamp","DEFAULT_FREQUENCY","DEFAULT_NAME","_frequency","round","NEVER","MAX_INTERVAL","phase","ticked","asyncIterator","DISPOSED_STATE","schedule","IMMEDIATE","next","pending","scheduled","payload","_execute","hidden","rejected","sleep","Infinity","DEFAULT_BACKOFF","growth","addEventListener","visibilityState","RateLimiter","limit","poll","Debouncer","invoke","Throttler","_trailing","edge","_interval","idle","_pid","nextPID","_create","_coerce","coerce","_compare","compare","owner","ensureMap","_createValue","_coerceValue","_maybeNotify","_compareValue","ownerData","WeakMap","ArrayExt","StringExt","firstIndexOf","array","span","j","findFirstIndex","findLastIndex","reverse","removeAt","findFirstValue","findLastValue","lowerBound","begin","half","middle","upperBound","shallowEqual","step","move","fromIndex","toIndex","rotate","pivot","fill","insert","removeFirstOf","removeLastOf","removeAllOf","count","removeFirstWhere","removeLastWhere","removeAllWhere","rangeLength","findIndices","source","indices","matchSumOfSquares","score","matchSumOfDeltas","highlight","cmp","thisArg","disconnectBetween","receiver","disconnectSender","disconnectReceiver","disconnectAll","getExceptionHandler","exceptionHandler","setExceptionHandler","handler","old","_pending","receivers","receiversForSender","connection","scheduleCleanup","sendersForReceiver","senders","findConnection","invokeSlot","dirtySet","cleanupDirtySet","cleanupConnections","isDeadConnection","module","createCommonjsModule","_global","global","self","Function","__g","_core","core","__e","_isObject","it","_anObject","_fails","exec","_descriptors","is","_ie8DomDefine","dP","_objectDp","f","O","P","Attributes","S","valueOf","_toPrimitive","_hide","bitmap","_propertyDesc","_has","px","_shared","SHARED","store","copyright","_functionToString","_redefine","SRC","_uid","TO_STRING","TPL","inspectSource","safe","isFunction","_ctx","that","_aFunction","c","apply","PROTOTYPE","$export","own","out","exp","IS_FORCED","F","IS_GLOBAL","G","IS_STATIC","IS_PROTO","IS_BIND","B","expProto","U","W","R","_export","_toInteger","isNaN","$at","pos","s","_defined","l","codePointAt","fromCharCode","$fromCodePoint","fromCodePoint","arguments$1","res","aLen","RangeError","parseState","column","lexState","doubleQuote","sign","unicode","Space_Separator","ID_Start","ID_Continue","util","isSpaceSeparator","isIdStartChar","isIdContinueChar","isDigit","isHexDigit","internalize","holder","reviver","replacement","key$1","replacement$1","lex","peek","lexStates","read","newToken","comment","invalidChar","multiLineComment","multiLineCommentAsterisk","singleLineComment","literal","NaN","identifierNameStartEscape","unicodeEscape","invalidIdentifier","identifierName","identifierNameEscape","zero","decimalInteger","decimalPointLeading","decimalPoint","decimalFraction","decimalExponent","decimalExponentSign","decimalExponentInteger","hexadecimal","hexadecimalInteger","string","parseInt","hexEscape","escape","formatChar","separatorChar","beforePropertyName","afterPropertyName","beforePropertyValue","afterPropertyValue","beforeArrayValue","afterArrayValue","end","parseStates","invalidEOF","pop","parent","syntaxError","replacements","hexString","SyntaxError","lineNumber","columnNumber","replacer","space","propertyList","replacerFunc","quote","indent","gap","substr","serializeProperty","toJSON5","toJSON","Boolean","quoteString","stepback","final","partial","propertyString","separator","properties$1","serializeArray","properties","member","serializeKey","serializeObject","quotes","product","quoteChar","RegExp","firstChar","getSerializerPromise","localForageInstance","getSerializer","executeCallback","storageRepository","_driver","_initStorage","dbInfo","database","table","storeName","db","_dbInfo","serializer","iterate","iterationNumber","originalValue","serializeAsync","removeItem","t","r","_dereq_","scheduleDrain","draining","Mutation","MutationObserver","WebKitMutationObserver","called","observer","nextTick","element","createTextNode","observe","characterData","MessageChannel","scriptEl","onreadystatechange","parentNode","removeChild","appendChild","port1","port2","postMessage","oldQueue","task","g","immediate","INTERNAL","handlers","REJECTED","FULFILLED","PENDING","resolver","outcome","safelyResolveThenable","QueueItem","onFulfilled","onRejected","callFulfilled","otherCallFulfilled","callRejected","otherCallRejected","unwrap","func","returnValue","getThen","thenable","onError","onSuccess","tryCatch","iterable","allResolver","outValue","race","_typeof","idb","indexedDB","webkitIndexedDB","mozIndexedDB","OIndexedDB","msIndexedDB","getIDB","createBlob","Blob","BlobBuilder","MSBlobBuilder","MozBlobBuilder","WebKitBlobBuilder","getBlob","Promise$1","executeTwoCallbacks","errorCallback","normalizeKey","getCallback","DETECT_BLOB_SUPPORT_STORE","supportsBlobs","dbContexts","READ_ONLY","READ_WRITE","_binStringToArrayBuffer","bin","arr","_checkBlobSupport","txn","transaction","blob","objectStore","put","onabort","preventDefault","stopPropagation","oncomplete","matchedChrome","navigator","userAgent","matchedEdge","_checkBlobSupportWithoutCaching","_deferReadiness","dbContext","deferredOperation","deferredOperations","dbReady","_advanceReadiness","_rejectReadiness","_getConnection","upgradeNeeded","forages","dbArgs","openreq","onupgradeneeded","createObjectStore","oldVersion","ex","newVersion","onsuccess","onversionchange","_getOriginalConnection","_getUpgradedConnection","_isUpgradeNeeded","defaultVersion","isNewStore","objectStoreNames","isDowngrade","isUpgrade","incVersion","_decodeBlob","encodedBlob","atob","_isEncodedBlob","__local_forage_encoded_blob","_fullyReady","_initReady","createTransaction","retries","tx","forage","_tryReconnect","asyncStorage","initPromises","ignoreErrors","_defaultConfig","_support","isSafari","openDatabase","platform","hasFetch","IDBKeyRange","isIndexedDBValid","req","openCursor","cursor","blobSupport","reader","FileReader","onloadend","base64","btoa","readAsBinaryString","advanced","openKeyCursor","advance","dropInstance","currentConfig","config","dbPromise","dropObjectPromise","deleteObjectStore","_forage2","dropDBPromise","deleteDatabase","onblocked","BASE_CHARS","BLOB_TYPE_PREFIX","BLOB_TYPE_PREFIX_REGEX","SERIALIZED_MARKER","SERIALIZED_MARKER_LENGTH","TYPE_ARRAYBUFFER","TYPE_BLOB","TYPE_INT8ARRAY","TYPE_UINT8ARRAY","TYPE_UINT8CLAMPEDARRAY","TYPE_INT16ARRAY","TYPE_INT32ARRAY","TYPE_UINT16ARRAY","TYPE_UINT32ARRAY","TYPE_FLOAT32ARRAY","TYPE_FLOAT64ARRAY","TYPE_SERIALIZED_MARKER_LENGTH","toString$1","stringToBuffer","serializedString","encoded1","encoded2","encoded3","encoded4","bufferLength","bufferToString","base64String","localforageSerializer","valueType","marker","fileReader","onload","readAsArrayBuffer","blobType","matcher","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","createDbTable","executeSql","tryExecuteSql","sqlStatement","SYNTAX_ERR","results","rows","_setItem","retriesLeft","sqlError","QUOTA_ERR","webSQLStorage","dbInfoPromise","storeNames","getAllStoreNames","operationInfo","dropTable","operations","_getKeyPrefix","defaultConfig","keyPrefix","_isLocalStorageUsable","localStorageTestKey","checkIfLocalStorageThrows","localStorageWrapper","isLocalStorageValid","keyPrefixLength","itemKey","searchElement","y","arg","DefinedDrivers","DriverSupport","DefaultDrivers","INDEXEDDB","WEBSQL","LOCALSTORAGE","DefaultDriverOrder","OptionalDriverMethods","LibraryMethods","DefaultConfig","driver","callWhenReady","libraryMethod","extend","_key","LocalForage","driverTypeKey","instance","Constructor","_classCallCheck","driverName","defineDriver","_config","_driverSet","_initDriver","_wrapLibraryMethodsWithReady","setDriver","driverObject","complianceError","driverMethods","driverMethodName","methodNotImplementedFactory","methodName","_i","_len","optionalDriverMethod","configureMissingMethods","setDriverSupport","support","getDriver","getDriverPromise","serializerPromise","drivers","supportedDrivers","_getSupportedDrivers","setDriverToConfig","extendSelfWithDriver","_extend","oldDriverSetDone","currentDriverIndex","driverPromiseLoop","initDriver","supports","libraryMethodsAndProperties","createInstance","localforage_js","isNumber","isConstructorOrProto","opts","flags","bools","strings","unknownFn","unknown","boolean","allBools","aliases","aliasIsBoolean","alias","setKey","lastKey","setArg","argDefined","notFlags","letters","broken","stopEarly","commonjsGlobal","requiresPort","port","input","querystringify_1","pairs","part","parser","CRHTLF","protocolre","windowsDriveLetter","whitespace","trimLeft","rules","address","isSpecial","ignore","hash","lolcation","loc","location","finaldestination","Url","unescape","scheme","extractProtocol","rest","forwardSlashes","otherSlashes","slashesCount","extracted","instruction","instructions","unshift","up","password","origin","char","ins","qs","urlParse","delay","context","timeoutContext","itemInArray","EventTarget","listeners","trimQueryPartFromURL","queryIndex","listener","removeEventListener","removingListener","arrayOfListeners","dispatchEvent","this$1","customArguments","eventName","NetworkBridge","urlMap","attachWebSocket","websocket","serverURL","connectionLookup","server","websockets","addMembershipToRoom","room","roomMemberships","attachServer","serverUrl","serverLookup","websocketsLookup","broadcaster","removeServer","removeWebSocket","removeMembershipFromRoom","memberships","networkBridge","CLOSE_CODES","CLOSE_NORMAL","CLOSE_GOING_AWAY","CLOSE_PROTOCOL_ERROR","CLOSE_UNSUPPORTED","CLOSE_NO_STATUS","CLOSE_ABNORMAL","UNSUPPORTED_DATA","POLICY_VIOLATION","CLOSE_TOO_LARGE","MISSING_EXTENSION","INTERNAL_ERROR","SERVICE_RESTART","TRY_AGAIN_LATER","TLS_HANDSHAKE","ERROR_PREFIX","CONSTRUCTOR_ERROR","CLOSE_ERROR","EVENT","CONSTRUCT","MESSAGE","CLOSE","EventPrototype","stopImmediatePropagation","initEvent","bubbles","cancelable","Event","EventPrototype$$1","eventInitConfig","timeStamp","srcElement","isTrusted","eventPhase","defaultPrevented","currentTarget","cancelBubble","__proto__","MessageEvent","lastEventId","ports","canncelBubble","CloseEvent","wasClean","createEvent","eventObject","createMessageEvent","messageEvent","createCloseEvent","closeEvent","closeWebSocketConnection","readyState","WebSocket$1","CLOSING","CLOSED","normalizeSendData","proxies","proxyFactory","proxy","Proxy","prop","toSocketName","EventTarget$$1","protocols","_onopen","_onmessage","_onerror","_onclose","urlRecord","urlVerification","uniq","duplicates","protocolVerification","CONNECTING","client","verifyClient","selectProtocol","selectedProtocol","isFilled","isRequested","OPEN","prototypeAccessors","errorEvent","failWebSocketConnection","defineProperties","SocketIO$1","SocketIO","broadcast","in","on","off","hasListeners","leave","IO","retrieveGlobalObject","defaultOptions","mock","Server$1","Server","originalWebSocket","assign","mockWebsocket","globalObj","restoreWebsocket","normalizedData","messageData","clients","broadcastList","deduped","chainedRoom","chainedBroadcaster","simulate","of","SocketIO$$1","assertPath","normalizeStringPosix","allowAboveRoot","lastSegmentLength","lastSlash","dots","lastSlashIndex","resolvedPath","resolvedAbsolute","isAbsolute","trailingSeparator","joined","fromStart","fromEnd","fromLen","toStart","toLen","lastCommonSep","fromCode","_makeLong","hasRoot","matchedSlash","extIdx","firstNonSlashEnd","startDot","startPart","preDotState","pathObject","sep","_format","ret","delimiter","win32","setupThebeLite","thebeLite","startJupyterLiteServer","serverExtensions","activePlugins","plugins","litePluginSettings","litePluginsToRegister","liteExtensionPromises","liteExtension","scope","_JUPYTERLAB","createModule","allSettled","jupyterLiteServer","JupyterLiteServer","registerPluginModules","serviceManager","extendStatics","setPrototypeOf","__extends","__","__assign","__rest","getOwnPropertySymbols","propertyIsEnumerable","__decorate","decorators","Reflect","decorate","__param","paramIndex","decorator","__metadata","metadataKey","metadataValue","__awaiter","_arguments","generator","fulfilled","__generator","label","sent","trys","ops","verb","op","__values","__read","ar","__spread","__spreadArrays","il","jl","__spreadArray","pack","__await","__asyncGenerator","q","resume","settle","__asyncDelegator","__asyncValues","__makeTemplateObject","cooked","__classPrivateFieldGet","kind","__classPrivateFieldSet","required","controlOrWhitespace","IContents","MIME","FILE","PLAIN_TEXT","OCTET_STREAM","TYPES","getType","defaultType","fileType","fileExt","extensions","mimeTypes","hasFormat","fileFormat","IBroadcastChannelWrapper","IKernels","FALLBACK_KERNEL","IKernelSpecs","KERNEL_ICON_URL","PLUGIN_ID","autoStart","requires","optional","activate","app","serviceWorker","broadcastChannel","pyodideUrl","pipliteWheelUrl","pipliteUrls","pipUrl","disablePyPIFallback","register","PyodideKernel","mountDrive","enabled","DEFAULT_STORAGE_NAME","reduceBytesToString","byte","_serverContents","_storageName","_storageDrivers","_localforage","localforage","storageName","storageDrivers","initStorage","createDefaultStorage","_counters","createDefaultCounters","_checkpoints","createDefaultCheckpoints","storage","counters","checkpoints","defaultStorageOptions","created","file","_incrementCounter","last_modified","mimetype","counter","EMPTY_NB","toPath","_getFolder","serverItem","_getServerContents","contentMap","serverContents","_getServerDirectory","modified","newFile","child","chunk","chunked","originalContent","lastChunk","_handleChunk","slashed","toDelete","forgetPath","copies","normalizeCheckpoint","newContent","escaped","fileUrl","ok","contentText","contentBytes","arrayBuffer","contentBuffer","apiURL","orig_nbformat","nbformat_minor","nbformat","cells","BroadcastChannelWrapper","_onMessage","_channel","_contents","subcontent","defaultDate","dev","nlink","uid","gid","rdev","blksize","blocks","atime","mtime","ctime","_enabled","enable","BroadcastChannel","disable","ObservableMap","_map","_itemCmp","itemCmp","oldVal","keyList","valList","E_CANCELED","__awaiter$2","Semaphore","_maxConcurrency","_cancelError","_queue","_waiters","_value","acquire","locked","isLocked","ticketPromise","_dispatch","runExclusive","release","waitForUnlock","_currentReleaser","releaser","ticket","nextTicket","released","_resolveWaiters","waiter","Mutex","cancelError","_semaphore","KERNEL_WEBSOCKET_PROTOCOL","Kernels","_kernels","_clients","_kernelClients","_kernelspecs","factories","mutex","kernelId","encodedData","handleMessage","processMsg","removeClient","kernelUrl","WS_BASE_URL","runningKernel","sendMessage","wsServer","KernelSpecs","_factories","defaultKernelName","fromEntries","THIRD_PARTY_LICENSES","ILicenses","EMPTY_BUNDLE","packages","Licenses","bundles","_getFederated","appName","_getAppLicenses","appLicensesUrl","labExtensionsUrl","bundle","federated","_getOneFederated","ISessions","Sessions","_sessions","patched","newKernel","_handleKernelShutdown","sessionId","kernelName","nameOrPath","ISettings","Settings","defaultSettingsStorage","pluginId","getAll","setting","allCore","allFederated","_getAll","override","settingsUrl","_overrides","schema","propDefault","entries","ITranslation","Translation","_prevLocale","locale","prev","displayName","nativeName","en","ILocalForage","localforagePlugin","provides","localforageMemoryPlugin","theLocalforage","ensureMemoryStorage","contentsPlugin","started","initialize","contentsRoutesPlugin","router","filename","Response","post","nb","copyFrom","patch","serviceWorkerPlugin","settingsPlugin","settingsRoutesPlugin","pluginPattern","serviceWorkerRegistrationWrapper","what","logStatus","allKernelSpecs","allSpecs","licenses","translation","ClipboardExt","Selector","Platform","ElementExt","getKeyboardLayout","keyboardLayout","copyText","clipboardData","execCommand","boxSizing","style","getComputedStyle","bt","parseFloat","borderTopWidth","bl","borderLeftWidth","br","borderRightWidth","bb","borderBottomWidth","pt","paddingTop","pl","paddingLeft","pr","paddingRight","pb","paddingBottom","borderTop","borderLeft","borderRight","borderBottom","horizontalSum","verticalSum","sizeLimits","minWidth","minHeight","maxWidth","maxHeight","hitTest","clientX","clientY","rect","getBoundingClientRect","left","right","top","bottom","scrollIntoViewIfNeeded","area","er","height","scrollTop","IS_MAC","IS_WIN","IS_IE","IS_EDGE","accelKey","metaKey","ctrlKey","calculateSpecificity","selector","specificityCache","calculateSingle","isValid","validityCache","testElem","querySelector","protoMatchFunc","proto","Element","matchesSelector","mozMatchesSelector","msMatchesSelector","oMatchesSelector","webkitMatchesSelector","elem","ownerDocument","querySelectorAll","re","NEGATION_RE","ID_RE","CLASS_RE","ATTR_RE","PSEUDO_ELEM_RE","PSEDUO_CLASS_RE","TYPE_RE","IGNORE_RE","KeycodeLayout","codes","modifierKeys","_codes","_keys","extractKeys","_modifierKeys","convertToKeySet","isValidKey","isModifierKey","keyForKeydownEvent","keyCode","keySet","EN_US","CommandRegistry","_timerID","_replaying","_keystrokes","_keydownEvents","_keyBindings","_exactKeyMatch","_commands","_commandChanged","_commandExecuted","_keyBindingChanged","commandChanged","commandExecuted","keyBindingChanged","keyBindings","listCommands","hasCommand","addCommand","createCommand","notifyCommandChanged","describedBy","cmd","mnemonic","icon","iconClass","iconLabel","caption","usage","isEnabled","isToggled","isToggleable","isVisible","addKeyBinding","binding","createKeyBinding","processKeydownEvent","isModifierKeyPressed","keystroke","keystrokeForKeydownEvent","_replayKeydownEvents","_clearPendingState","exact","matchKeyBinding","_executeKeyBinding","_startTimer","_clearTimer","_onPendingTimeout","CHORD_TIMEOUT","replayKeyEvent","newArgs","_luminoEvent","msg1","msg2","empty","parseKeystroke","alt","ctrl","normalizeKeystroke","mods","normalizeKeys","winKeys","macKeys","linuxKeys","formatKeystroke","formatSingleKey","formatKey","layout","altKey","shiftKey","asFunc","emptyStringFunc","negativeOneFunc","undefinedFunc","emptyDatasetFunc","trueFunc","falseFunc","validateSelector","bindings","distance","specificity","sqm","matchSequence","targetDistance","td","sp","which","cloneKeyboardEvent","MAC_DISPLAY","WIN_DISPLAY","Backspace","Tab","Enter","Shift","Ctrl","Alt","Escape","PageUp","PageDown","End","Home","ArrowLeft","ArrowUp","ArrowRight","ArrowDown","Delete","Cmd","dfault","bindKeys","userKeys","targ","curr","dist","parentElement","hasAttribute","LinkedList","_first","_last","_size","isEmpty","firstNode","lastNode","node","addLast","removeLast","addFirst","removeFirst","LinkedListNode","insertBefore","ref","_ref","insertAfter","removeNode","_node","Message","isConflatable","conflate","other","ConflatableMessage","MessageLoop","hooks","messageHooks","invokeHandler","passed","retro","messageHook","invokeHook","posted","messageQueue","enqueueMessage","installMessageHook","flush","flushGuard","runMessageLoop","processMessage","sentinel","cleanupHooks","isNull","_onScrollFrame","_scrollTarget","SCROLL_EDGE_SIZE","scrollLeft","_dropAction","_override","_currentTarget","_currentElement","_promise","mimeData","dragImage","proposedAction","supportedActions","PointerEvent","dispatchDragLeave","_finalize","_addListeners","_attachDragImage","handleEvent","_evtPointerMove","_evtPointerUp","_evtKeyDown","moveDragImage","_updateCurrentTarget","_updateDragScroll","button","action","dispatchDrop","_removeListeners","findScrollTarget","prevTarget","currTarget","prevElem","currElem","findElementBehindBackdrop","dispatchDragExit","dispatchDragEnter","dispatchDragOver","_setDropAction","classList","pointerEvents","position","Document","firstElementChild","_detachDragImage","validateAction","overrideCursor","Drag","DragEvent","detail","relatedTarget","related","screenX","screenY","drag","dropAction","doc","lastElementEventSearch","cursorBackdrop","zIndex","elementFromPoint","lastElementSearch","bbox","width","supported","actionTable","supportedTable","offsetX","offsetY","pageXOffset","pageYOffset","dl","dt","dr","shouldScroll","dsw","scrollWidth","clientWidth","dsh","scrollHeight","clientHeight","dragEvent","none","link","alignBackdrop","propagateBackdropScroll","_event","scrollTarget","closest","backdropScrollOrigin","resetBackdropScroll","overrideCursorID","isConnected","capture","passive","backdrop","createCursorBackdrop","VirtualDOM","BoxEngine","Private$j","Private$i","Utils","VirtualText","VirtualElement","tag","attrs","children","renderer","h","bind","abbr","article","aside","audio","bdi","bdo","blockquote","canvas","cite","col","colgroup","datalist","dd","del","dfn","div","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","hr","iframe","img","kbd","legend","li","main","mark","meter","nav","noscript","ol","optgroup","option","output","param","pre","progress","rp","rt","ruby","samp","select","small","strong","sub","summary","sup","tbody","textarea","tfoot","th","thead","time","title","tr","track","ul","var_","video","wbr","realize","createDOMNode","render","oldContent","hostMap","asContentArray","updateContent","before","specialAttrs","setAttribute","htmlFor","addDataset","elemStyle","addStyle","addAttrs","removeContent","newCount","_sentinel","oldNode","lastChild","childNodes","unrender","oldKeyed","firstChild","keyMap","vNode","nextSibling","collectKeys","oldCopy","oldVNode","newVNode","newKey","pair","oldKey","updateAttrs","oldAttrs","newAttrs","removeAttribute","oldDataset","newDataset","updateDataset","oldStyle","newStyle","updateStyle","BoxSizer","sizeHint","minSize","maxSize","stretch","calc","sizers","totalMin","totalMax","totalSize","totalStretch","stretchCount","sizer","hint","nearZero","notDoneCount","freeSpace","distSpace","distStretch","amt","adjust","growLimit","shrinkLimit","grow","shrink","growSizer","shrinkSizer","Title","_label","_caption","_mnemonic","_icon","_iconClass","_iconLabel","_closable","closable","_dataset","Widget","_flags","_layout","_parent","_hiddenMode","HiddenMode","Display","createNode","addClass","setFlag","Flag","IsDisposed","isAttached","detach","testFlag","IsAttached","isHidden","IsHidden","IsVisible","titleProperty","hiddenMode","_toggleHidden","Scale","willChange","ChildMessage","Msg","ParentChanged","DisallowLayout","widget","hasClass","removeClass","toggleClass","toggle","UpdateRequest","fit","FitRequest","ActivateRequest","CloseRequest","show","BeforeShow","clearFlag","AfterShow","hide","BeforeHide","AfterHide","setHidden","notifyLayout","onResize","onUpdateRequest","onFitRequest","onBeforeShow","onAfterShow","onBeforeHide","onAfterHide","onBeforeAttach","onAfterAttach","onBeforeDetach","onAfterDetach","onActivateRequest","onCloseRequest","onChildAdded","onChildRemoved","processParentMessage","ContentVisibility","contentVisibility","BeforeAttach","AfterAttach","BeforeDetach","AfterDetach","ResizeMessage","UnknownSize","attach","Layout","_fitPolicy","fitPolicy","onChildShown","onChildHidden","removeWidget","getHorizontalAlignment","horizontalAlignmentProperty","setHorizontalAlignment","getVerticalAlignment","verticalAlignmentProperty","setVerticalAlignment","LayoutItem","_top","_left","_width","_height","_minWidth","_minHeight","_maxWidth","_maxHeight","contain","limits","clampW","clampH","resized","onAlignmentChanged","PanelLayout","_widgets","widgets","addWidget","insertWidget","attachWidget","moveWidget","removeWidgetAt","detachWidget","clampDimension","Private$h","Private$g","Private$f","Private$e","Private$d","Private$c","Private$b","Private$a","Private$9","Private$8","Utils$1","SplitLayout","widgetOffset","_fixed","_spacing","_dirty","_hasNormedSizes","_sizers","_handles","_box","_alignment","_orientation","orientation","alignment","spacing","handles","absoluteSizes","relativeSizes","setRelativeSizes","sizes","temp","normed","moveHandle","handle","offsetLeft","offsetTop","createHandle","average","averageSize","createSizer","_update","_fit","updateItemPosition","isHorizontal","handleStyle","nVisible","lastHandleIndex","horz","minW","minH","getStretch","box","offsetWidth","offsetHeight","extra","offset","fullOffset","stretchProperty","setStretch","sum","abs","AccordionLayout","_titles","titleSpace","titles","updateTitle","oldTitle","expanded","newTitle","createTitle","replaceChild","titleStyle","createSectionTitle","Panel","createLayout","SplitPanel","_handleMoved","_pressData","_releaseMouse","handleMoved","_evtPointerDown","Renderer","defaultRenderer","AccordionPanel","_widgetSizesCache","_expansionToggled","expansionToggled","_onTitleChanged","collapse","_toggleExpansion","expand","_evtClick","_eventKeyDown","_computeWidgetSize","widgetSizes","newSize","previousSize","widgetToCollapse","sz","currentSize","click","newIndex","focus","titleClassName","_titleID","_titleKeys","_uuid","_nInstance","createCollapseIcon","createTitleKey","aData","BoxLayout","_direction","getSizeBasis","sizeBasisProperty","setSizeBasis","onChildSizingChanged","clampSpacing","BoxPanel","CommandPalette","_activeIndex","_results","commands","_onGenericChange","searchNode","getElementsByClassName","inputNode","contentNode","addItem","createItem","addItems","newItems","removeItemAt","clearItems","_toggleFocused","search","canActivate","renderEmptyMessage","activeIndex","category","renderHeader","active","renderItem","_activatePreviousItem","_activateNextItem","ai","focused","activeElement","formatHeader","createItemClass","createItemDataset","role","renderItemIcon","renderItemContent","renderItemShortcut","formatEmptyMessage","createIconClass","renderItemLabel","renderItemCaption","formatItemLabel","formatItemCaption","formatItemShortcut","kb","keyBinding","fuzzySearch","rgx","rgxMatch","categoryIndices","labelIndices","matchType","scoreCmp","m1","d1","i1","i2","localeCompare","r1","rank","r2","wrapper","spellcheck","CommandItem","scores","matchItems","visited","createResults","trim","Menu","_childIndex","_openTimerID","_closeTimerID","_childMenu","_parentMenu","_aboutToClose","_menuRequested","aboutToClose","menuRequested","parentMenu","childMenu","rootMenu","menu","leafMenu","activeItem","activateNextItem","activatePreviousItem","triggerActiveItem","_cancelOpenTimer","_cancelCloseTimer","_openChildMenu","insertItem","forceX","forceY","openRootMenu","_evtMouseUp","_evtMouseMove","_evtMouseEnter","_evtMouseLeave","_evtMouseDown","collapsedFlags","computeCollapsed","collapsed","onfocus","findMnemonic","multiple","_startCloseTimer","submenu","_startOpenTimer","hitTestMenus","activateFirst","_closeChildMenu","saveWindowData","itemNode","openSubmenu","TIMER_DELAY","aria","createItemARIA","tabindex","renderIcon","renderLabel","renderShortcut","renderSubmenu","formatLabel","formatShortcut","suffix","SUBMENU_OVERLAP","transientWindowDataCache","transientCacheCounter","getWindowData","_getWindowData","tabIndex","MenuItem","k1","windowData","py","cw","ch","opacity","itemRect","upperKey","mn","ContextMenu","_groupByTarget","_idTick","_sortBySelector","groupByTarget","sortBySelector","others","itemCmpRank","s1","s2","availableItems","ARROW_KEYS","TabBar","Private$7","_currentIndex","_titlesEditable","_previousTitle","_dragData","_addButtonEnabled","_tabMoved","_addRequested","_tabCloseRequested","_tabDetachRequested","_tabActivateRequested","_document","tabsMovable","titlesEditable","allowDeselect","addButtonEnabled","insertBehavior","removeBehavior","tabMoved","tabActivateRequested","addRequested","tabCloseRequested","tabDetachRequested","currentTitle","currentIndex","pi","ci","ct","previousIndex","previousTitle","addButtonNode","addTab","insertTab","asTitle","_adjustCurrentForInsert","_adjustCurrentForMove","removeTab","removeTabAt","_adjustCurrentForRemove","clearTabs","releaseMouse","_evtDblClick","CAPTURING_PHASE","_evtKeyDownCapturing","tabHandlingTabindex","_getCurrentTabindex","renderTab","elemTabindex","getAttribute","tabs","tab","innerHTML","onblur","focusedElement","focusable","nextFocused","focusedIndex","addButtonClicked","pressX","pressY","tabPos","tabSize","tabPressPos","targetIndex","tabLayout","contentRect","dragActive","dragAborted","detachRequested","closeIconSelector","dragExceeded","tabRect","tabPressOffset","snapTabLayout","detachExceeded","layoutTabs","finalizeTabPosition","duration","parseTransitionDuration","resetTabPositions","bh","Private$6","Private$5","Private$4","Private$3","Private$2","Private$1","_tabID","_tabKeys","createTabKey","createTabStyle","createTabClass","createTabDataset","createTabARIA","renderCloseIcon","addButtonSelector","DRAG_THRESHOLD","DETACH_THRESHOLD","transitionDuration","margin","marginLeft","marginTop","dx","dy","pressPos","localPos","clientPos","clientSize","targetPos","targetEnd","pxPos","threshold","ideal","tgt","DockLayout","_root","bar","tabBars","iterAllWidgets","iterUserWidgets","selectedWidgets","iterSelectedWidgets","iterTabBars","iterHandles","findSplitNode","holdSizes","saveLayout","holdAllSizes","createConfig","restoreLayout","mainConfig","widgetSet","normalizeAreaConfig","oldWidgets","oldTabBars","oldHandles","tabBar","realizeAreaConfig","createTabBar","_createTabBar","_createHandle","refNode","findTabNode","_insertTab","_insertSplit","_removeWidget","hitTestTabAreas","tabNode","hitTestTabNodes","borderWidth","borderHeight","removeAria","splitNode","syncHandles","maybeParent","childNode","childHandle","TabLayoutNode","splitHandle","gChild","gHandle","gSizer","_createTabNode","addAria","after","findFirstTabNode","merge","_splitRoot","normalizeSizes","GOLDEN_RATIO","sibling","SplitLayoutNode","oldRoot","newRoot","normalizeTabAreaConfig","normalizeSplitAreaConfig","realizeTabAreaConfig","realizeSplitAreaConfig","tabSizer","widgetSizer","tabBarItem","widgetItem","tabBarSizer","createNormalizedSizes","horizontal","fixed","tabId","DockPanel","_drag","_tabsMovable","_tabsConstrained","_layoutModified","_mode","_renderer","_edges","edges","DEFAULT_EDGES","tabsConstrained","overlay","Overlay","layoutModified","createSingleDocumentConfig","LayoutModified","selectWidget","activateWidget","_evtDragEnter","_evtDragLeave","_evtDragOver","_evtDrop","isGeneratedTabBarProperty","_showOverlay","zone","findDropTarget","getDropRef","deltaX","deltaY","xPos","yPos","tabHeight","_onTabMoved","_onCurrentChanged","_onTabCloseRequested","_onTabDetachRequested","_onTabActivateRequested","_onTabAddRequested","cloneNode","_hidden","geo","panel","selected","panelRect","al","at","ab","rx","ry","GridLayout","_rowSpacing","_columnSpacing","_rowStarts","_columnStarts","_rowSizers","_columnSizers","rowCount","reallocSizers","columnCount","rowSpacing","clampValue","columnSpacing","rowStretch","setRowStretch","columnStretch","setColumnStretch","maxRow","maxCol","rowSpanCmp","getCellConfig","row","rowSpan","distributeMin","columnSpanCmp","c1","c2","columnSpan","fixedRowSpace","fixedColSpace","w","cellConfigProperty","setCellConfig","normalizeConfig","portion","MenuBar","_tabFocusIndex","_menus","_overflowMenu","_menuItemSizes","_overflowIndex","_forceItemsPosition","forceItemsPosition","_overflowMenuOptions","overflowMenuOptions","overflowIndex","overflowMenu","activeMenu","menus","openActiveMenu","addMenu","insertMenu","_onMenuAboutToClose","_onMenuMenuRequested","removeMenu","removeMenuAt","clearMenus","_evtFocusOut","_focusItemAt","tabFocusIndex","totalMenuSize","tabbable","overflowMenuTitle","overflowMenuItems","screenSize","_updateOverflowIndex","itemMenus","_positionForMenu","newMenu","oldMenu","decrement","increment","thumb","findPart","scrollBar","thumbNode","trackNode","decrementNode","incrementNode","SingletonLayout","_widget","StackedLayout","orientationFromPlacement","plc","placementToOrientationMap","directionFromPlacement","placementToDirectionMap","Application","_delegate","_plugins","_services","_started","_bubblingKeydown","contextMenu","contextMenuRenderer","shell","getPluginDescription","hasPlugin","isPluginActivated","activated","listPlugins","registerPlugin","createPluginData","ensureNoCycle","registerPlugins","deregisterPlugin","ReferenceError","resolveRequiredService","resolveOptionalService","services","service","deactivate","manifest","findDependents","downstream","activatePlugin","bubblingKeydown","hostID","collectStartupPlugins","attachShell","addEventListeners","deferredPlugins","evtResize","evtKeydown","evtContextMenu","dependencies","visit","trace","dep","newEdges","oldSize","packagesOfInterest","poi","sorted","graph","addEdge","fromNode","toNode","candidate","collection","startPlugins","ignorePlugins","Router","_routes","pattern","_add","MockEventManager","_serverSettings","_router","_serviceManager","route","registerPluginModule","ServiceWorkerManager","_registration","_registrationChanged","workerUrl","registrationChanged","registration","controller","getRegistration","scriptURL","setRegistration","CACHE","openCache","caches","updateCache","skipWaiting","waitUntil","addAll","cacheAll","claim","responsePromise","shouldBroadcast","shouldDrop","fromCache","fromServer","refetch","maybeFromCache","broadcastOne","respondWith","IServiceWorkerManager","WORKER_NAME","Mime","_extensions","define","getExtension","typeMap","hasPath","$1","__webpack_module_cache__","leafPrototypes","getProto","inProgress","dataWebpackPrefix","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","getter","getPrototypeOf","ns","def","getOwnPropertyNames","definition","chunkId","globalThis","script","needAttach","scripts","getElementsByTagName","charset","nc","src","onScriptComplete","doneFns","head","toStringTag","scriptUrl","importScripts","currentScript","baseURI","installedChunks","installedChunkData","errorType","realSrc","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","chunkLoadingGlobal","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"thebe-lite.min.js","mappings":";2DAGAA,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IACtDD,EAAQE,iBAAc,EACtB,MAAMC,EAAc,EAAQ,KACtBC,EAAqB,EAAQ,MAsCnCJ,EAA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AAgC,IAAxByxG,EAAgBzxG,KAAa,CACtD,IAAI8vG,KAAYkC,EACZnC,oBAAoBt5G,EAAEy7G,EAAalC,KACrCD,oBAAoBr5G,EAAEs5G,GAAYkC,EAAYlC,IAG7CmC,GAAsBA,EAAQpC,oBAClC,CAEA,IADGiC,GAA4BA,EAA2B59G,GACrDqJ,EAAIw0G,EAAS34G,OAAQmE,IACzBizG,EAAUuB,EAASx0G,GAChBsyG,oBAAoBt5G,EAAEk7G,EAAiBjB,IAAYiB,EAAgBjB,IACrEiB,EAAgBjB,GAAS,KAE1BiB,EAAgBjB,GAAW,CAC5B,EAIG0B,EAAqB72E,KAA6B,uBAAIA,KAA6B,wBAAK,GAC5F62E,EAAmBppG,QAAQ+oG,EAAqBl9B,KAAK,KAAM,IAC3Du9B,EAAmB93G,KAAOy3G,EAAqBl9B,KAAK,KAAMu9B,EAAmB93G,KAAKu6E,KAAKu9B,QClFvF,IAAIC,oBAAsBtC,oBAAoB","sources":["webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/basemanager.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/builder/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/config/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/contents/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/contents/validate.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/event/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/comm.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/default.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/future.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/kernel.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/manager.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/messages.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/restapi.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/serialize.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernel/validate.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernelspec/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernelspec/kernelspec.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernelspec/manager.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernelspec/restapi.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/kernelspec/validate.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/manager.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/nbconvert/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/serverconnection.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/session/default.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/session/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/session/manager.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/session/restapi.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/session/session.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/session/validate.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/setting/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/shim/ws.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/terminal/default.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/terminal/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/terminal/manager.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/terminal/restapi.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/terminal/terminal.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/user/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/validate.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/lib/workspace/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/activitymonitor.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/interfaces.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/markdowncodeblocks.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/pageconfig.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/path.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/signal.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/text.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/time.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/coreutils/lib/url.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/statedb/lib/dataconnector.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/statedb/lib/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/statedb/lib/interfaces.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/statedb/lib/restorablepool.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/statedb/lib/statedb.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@jupyterlab/statedb/lib/tokens.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@lumino/coreutils/dist/index.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@lumino/disposable/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@lumino/polling/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@lumino/properties/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@lumino/algorithm/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@jupyterlab/services/node_modules/@lumino/signaling/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/coreutils/dist/index.js","webpack://thebe-lite/../../node_modules/json5/dist/index.js","webpack://thebe-lite/../../node_modules/localforage-memoryStorageDriver/dist/localforage-memoryStorageDriver.js","webpack://thebe-lite/../../node_modules/localforage/dist/localforage.js","webpack://thebe-lite/../../node_modules/minimist/index.js","webpack://thebe-lite/../../node_modules/mock-socket/dist/mock-socket.js","webpack://thebe-lite/../../node_modules/path-browserify/index.js","webpack://thebe-lite/../../node_modules/querystringify/index.js","webpack://thebe-lite/../../node_modules/requires-port/index.js","webpack://thebe-lite/./src/index.ts","webpack://thebe-lite/./src/jlite.ts","webpack://thebe-lite/../../node_modules/tslib/tslib.es6.js","webpack://thebe-lite/../../node_modules/url-parse/index.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/activitymonitor.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/index.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/interfaces.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/markdowncodeblocks.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/pageconfig.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/path.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/signal.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/text.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/time.js","webpack://thebe-lite/./node_modules/@jupyterlab/coreutils/lib/url.js","webpack://thebe-lite/./node_modules/@jupyterlite/contents/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/kernel/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/pyodide-kernel-extension/lib/index.js","webpack://thebe-lite/./node_modules/@jupyterlite/contents/lib/contents.js","webpack://thebe-lite/./node_modules/@jupyterlite/contents/lib/emscripten.js","webpack://thebe-lite/./node_modules/@jupyterlite/contents/lib/drivefs.js","webpack://thebe-lite/./node_modules/@jupyterlite/contents/lib/broadcast.js","webpack://thebe-lite/./node_modules/@jupyterlab/observables/lib/observablemap.js","webpack://thebe-lite/../../node_modules/async-mutex/index.mjs","webpack://thebe-lite/./node_modules/@jupyterlite/kernel/lib/kernels.js","webpack://thebe-lite/./node_modules/@jupyterlite/kernel/lib/kernelspecs.js","webpack://thebe-lite/./node_modules/@jupyterlite/licenses/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/licenses/lib/licenses.js","webpack://thebe-lite/./node_modules/@jupyterlite/session/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/session/lib/sessions.js","webpack://thebe-lite/./node_modules/@jupyterlite/settings/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/settings/lib/settings.js","webpack://thebe-lite/./node_modules/@jupyterlite/translation/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/translation/lib/translation.js","webpack://thebe-lite/./node_modules/@jupyterlite/localforage/lib/tokens.js","webpack://thebe-lite/./node_modules/@jupyterlite/server-extension/lib/index.js","webpack://thebe-lite/./node_modules/@jupyterlite/localforage/lib/memory.js","webpack://thebe-lite/./node_modules/@lumino/domutils/dist/index.es6.js","webpack://thebe-lite/./node_modules/@lumino/disposable/dist/index.es6.js","webpack://thebe-lite/./node_modules/@lumino/keyboard/dist/index.es6.js","webpack://thebe-lite/./node_modules/@lumino/commands/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/algorithm/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/domutils/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/collections/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/messaging/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/properties/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/signaling/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/dragdrop/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/disposable/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/keyboard/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/commands/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/node_modules/@lumino/virtualdom/dist/index.es6.js","webpack://thebe-lite/../../node_modules/@lumino/widgets/dist/index.es6.js","webpack://thebe-lite/./node_modules/@lumino/application/dist/index.es6.js","webpack://thebe-lite/./node_modules/@jupyterlite/server/lib/router.js","webpack://thebe-lite/./node_modules/@jupyterlite/server/lib/app.js","webpack://thebe-lite/./node_modules/@jupyterlite/server/lib/service-manager.js","webpack://thebe-lite/./node_modules/@jupyterlite/server/lib/tokens.js","webpack://thebe-lite/./node_modules/@lumino/algorithm/dist/index.es6.js","webpack://thebe-lite/./node_modules/@lumino/coreutils/dist/index.js","webpack://thebe-lite/./node_modules/@lumino/signaling/dist/index.es6.js","webpack://thebe-lite/./node_modules/mime/Mime.js","webpack://thebe-lite/./node_modules/mime/index.js","webpack://thebe-lite/./node_modules/mime/types/other.js","webpack://thebe-lite/./node_modules/mime/types/standard.js","webpack://thebe-lite/./src/empty.js","webpack://thebe-lite/webpack/bootstrap","webpack://thebe-lite/webpack/runtime/create fake namespace object","webpack://thebe-lite/webpack/runtime/load script","webpack://thebe-lite/webpack/runtime/amd options","webpack://thebe-lite/webpack/runtime/compat get default export","webpack://thebe-lite/webpack/runtime/define property getters","webpack://thebe-lite/webpack/runtime/ensure chunk","webpack://thebe-lite/webpack/runtime/get javascript chunk filename","webpack://thebe-lite/webpack/runtime/global","webpack://thebe-lite/webpack/runtime/hasOwnProperty shorthand","webpack://thebe-lite/webpack/runtime/make namespace object","webpack://thebe-lite/webpack/runtime/publicPath","webpack://thebe-lite/webpack/runtime/jsonp chunk loading","webpack://thebe-lite/webpack/startup"],"sourcesContent":["\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BaseManager = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"./serverconnection\");\nclass BaseManager {\n constructor(options) {\n var _a;\n this._isDisposed = false;\n this._disposed = new signaling_1.Signal(this);\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return true;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._disposed.emit(undefined);\n signaling_1.Signal.clearData(this);\n }\n}\nexports.BaseManager = BaseManager;\n//# sourceMappingURL=basemanager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BuildManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the lab build service.\n */\nconst BUILD_SETTINGS_URL = 'api/build';\n/**\n * The build API service manager.\n */\nclass BuildManager {\n /**\n * Create a new setting manager.\n */\n constructor(options = {}) {\n var _a;\n this._url = '';\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n const { baseUrl, appUrl } = this.serverSettings;\n this._url = coreutils_1.URLExt.join(baseUrl, appUrl, BUILD_SETTINGS_URL);\n }\n /**\n * Test whether the build service is available.\n */\n get isAvailable() {\n return coreutils_1.PageConfig.getOption('buildAvailable').toLowerCase() === 'true';\n }\n /**\n * Test whether to check build status automatically.\n */\n get shouldCheck() {\n return coreutils_1.PageConfig.getOption('buildCheck').toLowerCase() === 'true';\n }\n /**\n * Get whether the application should be built.\n */\n getStatus() {\n const { _url, serverSettings } = this;\n const promise = serverconnection_1.ServerConnection.makeRequest(_url, {}, serverSettings);\n return promise\n .then(response => {\n if (response.status !== 200) {\n throw new serverconnection_1.ServerConnection.ResponseError(response);\n }\n return response.json();\n })\n .then(data => {\n if (typeof data.status !== 'string') {\n throw new Error('Invalid data');\n }\n if (typeof data.message !== 'string') {\n throw new Error('Invalid data');\n }\n return data;\n });\n }\n /**\n * Build the application.\n */\n build() {\n const { _url, serverSettings } = this;\n const init = { method: 'POST' };\n const promise = serverconnection_1.ServerConnection.makeRequest(_url, init, serverSettings);\n return promise.then(response => {\n if (response.status === 400) {\n throw new serverconnection_1.ServerConnection.ResponseError(response, 'Build aborted');\n }\n if (response.status !== 200) {\n const message = `Build failed with ${response.status}.\n\n If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').\n\n If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;\n throw new serverconnection_1.ServerConnection.ResponseError(response, message);\n }\n });\n }\n /**\n * Cancel an active build.\n */\n cancel() {\n const { _url, serverSettings } = this;\n const init = { method: 'DELETE' };\n const promise = serverconnection_1.ServerConnection.makeRequest(_url, init, serverSettings);\n return promise.then(response => {\n if (response.status !== 204) {\n throw new serverconnection_1.ServerConnection.ResponseError(response);\n }\n });\n }\n}\nexports.BuildManager = BuildManager;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ConfigWithDefaults = exports.ConfigSection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst __1 = require(\"..\");\n/**\n * The url for the config service.\n */\nconst SERVICE_CONFIG_URL = 'api/config';\n/**\n * The namespace for ConfigSection statics.\n */\nvar ConfigSection;\n(function (ConfigSection) {\n /**\n * Create a config section.\n *\n * @returns A Promise that is fulfilled with the config section is loaded.\n */\n function create(options) {\n const section = new DefaultConfigSection(options);\n return section.load().then(() => {\n return section;\n });\n }\n ConfigSection.create = create;\n})(ConfigSection = exports.ConfigSection || (exports.ConfigSection = {}));\n/**\n * Implementation of the Configurable data section.\n */\nclass DefaultConfigSection {\n /**\n * Construct a new config section.\n */\n constructor(options) {\n var _a;\n this._url = 'unknown';\n const settings = (this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings());\n this._url = coreutils_1.URLExt.join(settings.baseUrl, SERVICE_CONFIG_URL, encodeURIComponent(options.name));\n }\n /**\n * Get the data for this section.\n */\n get data() {\n return this._data;\n }\n /**\n * Load the initial data for this section.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async load() {\n const response = await __1.ServerConnection.makeRequest(this._url, {}, this.serverSettings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._data = await response.json();\n }\n /**\n * Modify the stored config values.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * Updates the local data immediately, sends the change to the server,\n * and updates the local data with the response, and fulfils the promise\n * with that data.\n */\n async update(newdata) {\n this._data = { ...this._data, ...newdata };\n const init = {\n method: 'PATCH',\n body: JSON.stringify(newdata)\n };\n const response = await __1.ServerConnection.makeRequest(this._url, init, this.serverSettings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._data = await response.json();\n return this._data;\n }\n}\n/**\n * Configurable object with defaults.\n */\nclass ConfigWithDefaults {\n /**\n * Create a new config with defaults.\n */\n constructor(options) {\n var _a, _b;\n this._className = '';\n this._section = options.section;\n this._defaults = (_a = options.defaults) !== null && _a !== void 0 ? _a : {};\n this._className = (_b = options.className) !== null && _b !== void 0 ? _b : '';\n }\n /**\n * Get data from the config section or fall back to defaults.\n */\n get(key) {\n const data = this._classData();\n return key in data ? data[key] : this._defaults[key];\n }\n /**\n * Set a config value.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * Sends the update to the server, and changes our local copy of the data\n * immediately.\n */\n set(key, value) {\n const d = {};\n d[key] = value;\n if (this._className) {\n const d2 = {};\n d2[this._className] = d;\n return this._section.update(d2);\n }\n else {\n return this._section.update(d);\n }\n }\n /**\n * Get data from the Section with our classname, if available.\n *\n * #### Notes\n * If we have no classname, get all of the data in the Section\n */\n _classData() {\n const data = this._section.data;\n if (this._className && this._className in data) {\n return data[this._className];\n }\n return data;\n }\n}\nexports.ConfigWithDefaults = ConfigWithDefaults;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Drive = exports.ContentsManager = exports.Contents = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst validate = __importStar(require(\"./validate\"));\n/**\n * The url for the default drive service.\n */\nconst SERVICE_DRIVE_URL = 'api/contents';\n/**\n * The url for the file access.\n */\nconst FILES_URL = 'files';\n/**\n * A namespace for contents interfaces.\n */\nvar Contents;\n(function (Contents) {\n /**\n * Validates an IModel, throwing an error if it does not pass.\n */\n function validateContentsModel(contents) {\n validate.validateContentsModel(contents);\n }\n Contents.validateContentsModel = validateContentsModel;\n /**\n * Validates an ICheckpointModel, throwing an error if it does not pass.\n */\n function validateCheckpointModel(checkpoint) {\n validate.validateCheckpointModel(checkpoint);\n }\n Contents.validateCheckpointModel = validateCheckpointModel;\n})(Contents = exports.Contents || (exports.Contents = {}));\n/**\n * A contents manager that passes file operations to the server.\n * Multiple servers implementing the `IDrive` interface can be\n * attached to the contents manager, so that the same session can\n * perform file operations on multiple backends.\n *\n * This includes checkpointing with the normal file operations.\n */\nclass ContentsManager {\n /**\n * Construct a new contents manager object.\n *\n * @param options - The options used to initialize the object.\n */\n constructor(options = {}) {\n var _a, _b;\n this._isDisposed = false;\n this._additionalDrives = new Map();\n this._fileChanged = new signaling_1.Signal(this);\n const serverSettings = (this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings());\n this._defaultDrive = (_b = options.defaultDrive) !== null && _b !== void 0 ? _b : new Drive({ serverSettings });\n this._defaultDrive.fileChanged.connect(this._onFileChanged, this);\n }\n /**\n * A signal emitted when a file operation takes place.\n */\n get fileChanged() {\n return this._fileChanged;\n }\n /**\n * Test whether the manager has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * Add an `IDrive` to the manager.\n */\n addDrive(drive) {\n this._additionalDrives.set(drive.name, drive);\n drive.fileChanged.connect(this._onFileChanged, this);\n }\n /**\n * Given a path, get a shared model factory from the\n * relevant backend. Returns `null` if the backend\n * does not provide one.\n */\n getSharedModelFactory(path) {\n var _a;\n const [drive] = this._driveForPath(path);\n return (_a = drive === null || drive === void 0 ? void 0 : drive.sharedModelFactory) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the local part of it.\n *\n * @param path: the path.\n *\n * @returns The local part of the path.\n */\n localPath(path) {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1 || !this._additionalDrives.has(firstParts[0])) {\n return coreutils_1.PathExt.removeSlash(path);\n }\n return coreutils_1.PathExt.join(firstParts.slice(1).join(':'), ...parts.slice(1));\n }\n /**\n * Normalize a global path. Reduces '..' and '.' parts, and removes\n * leading slashes from the local part of the path, while retaining\n * the drive name if it exists.\n *\n * @param path: the path.\n *\n * @returns The normalized path.\n */\n normalize(path) {\n const parts = path.split(':');\n if (parts.length === 1) {\n return coreutils_1.PathExt.normalize(path);\n }\n return `${parts[0]}:${coreutils_1.PathExt.normalize(parts.slice(1).join(':'))}`;\n }\n /**\n * Resolve a global path, starting from the root path. Behaves like\n * posix-path.resolve, with 3 differences:\n * - will never prepend cwd\n * - if root has a drive name, the result is prefixed with \":\"\n * - before adding drive name, leading slashes are removed\n *\n * @param path: the path.\n *\n * @returns The normalized path.\n */\n resolvePath(root, path) {\n const driveName = this.driveName(root);\n const localPath = this.localPath(root);\n const resolved = coreutils_1.PathExt.resolve('/', localPath, path);\n return driveName ? `${driveName}:${resolved}` : resolved;\n }\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the name of the drive. If the path is missing\n * a drive portion, returns an empty string.\n *\n * @param path: the path.\n *\n * @returns The drive name for the path, or the empty string.\n */\n driveName(path) {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1) {\n return '';\n }\n if (this._additionalDrives.has(firstParts[0])) {\n return firstParts[0];\n }\n return '';\n }\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n *\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n get(path, options) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.get(localPath, options).then(contentsModel => {\n const listing = [];\n if (contentsModel.type === 'directory' && contentsModel.content) {\n for (const item of contentsModel.content) {\n listing.push({ ...item, path: this._toGlobalPath(drive, item.path) });\n }\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive, localPath),\n content: listing,\n serverPath: contentsModel.path\n };\n }\n else {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive, localPath),\n serverPath: contentsModel.path\n };\n }\n });\n }\n /**\n * Get an encoded download url given a file path.\n *\n * @param path - An absolute POSIX file path on the server.\n *\n * #### Notes\n * It is expected that the path contains no relative paths.\n *\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.getDownloadUrl(localPath);\n }\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n */\n newUntitled(options = {}) {\n if (options.path) {\n const globalPath = this.normalize(options.path);\n const [drive, localPath] = this._driveForPath(globalPath);\n return drive\n .newUntitled({ ...options, path: localPath })\n .then(contentsModel => {\n return {\n ...contentsModel,\n path: coreutils_1.PathExt.join(globalPath, contentsModel.name),\n serverPath: contentsModel.path\n };\n });\n }\n else {\n return this._defaultDrive.newUntitled(options);\n }\n }\n /**\n * Delete a file.\n *\n * @param path - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n */\n delete(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.delete(localPath);\n }\n /**\n * Rename a file or directory.\n *\n * @param path - The original file path.\n *\n * @param newPath - The new file path.\n *\n * @returns A promise which resolves with the new file contents model when\n * the file is renamed.\n */\n rename(path, newPath) {\n const [drive1, path1] = this._driveForPath(path);\n const [drive2, path2] = this._driveForPath(newPath);\n if (drive1 !== drive2) {\n throw Error('ContentsManager: renaming files must occur within a Drive');\n }\n return drive1.rename(path1, path2).then(contentsModel => {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive1, path2),\n serverPath: contentsModel.path\n };\n });\n }\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n */\n save(path, options = {}) {\n const globalPath = this.normalize(path);\n const [drive, localPath] = this._driveForPath(path);\n return drive\n .save(localPath, { ...options, path: localPath })\n .then(contentsModel => {\n return {\n ...contentsModel,\n path: globalPath,\n serverPath: contentsModel.path\n };\n });\n }\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n copy(fromFile, toDir) {\n const [drive1, path1] = this._driveForPath(fromFile);\n const [drive2, path2] = this._driveForPath(toDir);\n if (drive1 === drive2) {\n return drive1.copy(path1, path2).then(contentsModel => {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive1, contentsModel.path),\n serverPath: contentsModel.path\n };\n });\n }\n else {\n throw Error('Copying files between drives is not currently implemented');\n }\n }\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n createCheckpoint(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.createCheckpoint(localPath);\n }\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n listCheckpoints(path) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.listCheckpoints(localPath);\n }\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n restoreCheckpoint(path, checkpointID) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.restoreCheckpoint(localPath, checkpointID);\n }\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n deleteCheckpoint(path, checkpointID) {\n const [drive, localPath] = this._driveForPath(path);\n return drive.deleteCheckpoint(localPath, checkpointID);\n }\n /**\n * Given a drive and a local path, construct a fully qualified\n * path. The inverse of `_driveForPath`.\n *\n * @param drive: an `IDrive`.\n *\n * @param localPath: the local path on the drive.\n *\n * @returns the fully qualified path.\n */\n _toGlobalPath(drive, localPath) {\n if (drive === this._defaultDrive) {\n return coreutils_1.PathExt.removeSlash(localPath);\n }\n else {\n return `${drive.name}:${coreutils_1.PathExt.removeSlash(localPath)}`;\n }\n }\n /**\n * Given a path, get the `IDrive to which it refers,\n * where the path satisfies the pattern\n * `'driveName:path/to/file'`. If there is no `driveName`\n * prepended to the path, it returns the default drive.\n *\n * @param path: a path to a file.\n *\n * @returns A tuple containing an `IDrive` object for the path,\n * and a local path for that drive.\n */\n _driveForPath(path) {\n const driveName = this.driveName(path);\n const localPath = this.localPath(path);\n if (driveName) {\n return [this._additionalDrives.get(driveName), localPath];\n }\n else {\n return [this._defaultDrive, localPath];\n }\n }\n /**\n * Respond to fileChanged signals from the drives attached to\n * the manager. This prepends the drive name to the path if necessary,\n * and then forwards the signal.\n */\n _onFileChanged(sender, args) {\n var _a, _b;\n if (sender === this._defaultDrive) {\n this._fileChanged.emit(args);\n }\n else {\n let newValue = null;\n let oldValue = null;\n if ((_a = args.newValue) === null || _a === void 0 ? void 0 : _a.path) {\n newValue = {\n ...args.newValue,\n path: this._toGlobalPath(sender, args.newValue.path)\n };\n }\n if ((_b = args.oldValue) === null || _b === void 0 ? void 0 : _b.path) {\n oldValue = {\n ...args.oldValue,\n path: this._toGlobalPath(sender, args.oldValue.path)\n };\n }\n this._fileChanged.emit({\n type: args.type,\n newValue,\n oldValue\n });\n }\n }\n}\nexports.ContentsManager = ContentsManager;\n/**\n * A default implementation for an `IDrive`, talking to the\n * server using the Jupyter REST API.\n */\nclass Drive {\n /**\n * Construct a new contents manager object.\n *\n * @param options - The options used to initialize the object.\n */\n constructor(options = {}) {\n var _a, _b, _c;\n this._isDisposed = false;\n this._fileChanged = new signaling_1.Signal(this);\n this.name = (_a = options.name) !== null && _a !== void 0 ? _a : 'Default';\n this._apiEndpoint = (_b = options.apiEndpoint) !== null && _b !== void 0 ? _b : SERVICE_DRIVE_URL;\n this.serverSettings =\n (_c = options.serverSettings) !== null && _c !== void 0 ? _c : __1.ServerConnection.makeSettings();\n }\n /**\n * A signal emitted when a file operation takes place.\n */\n get fileChanged() {\n return this._fileChanged;\n }\n /**\n * Test whether the manager has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * Get a file or directory.\n *\n * @param localPath: The path to the file.\n *\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n *\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async get(localPath, options) {\n let url = this._getUrl(localPath);\n if (options) {\n // The notebook type cannot take an format option.\n if (options.type === 'notebook') {\n delete options['format'];\n }\n const content = options.content ? '1' : '0';\n const params = { ...options, content };\n url += coreutils_1.URLExt.objectToQueryString(params);\n }\n const settings = this.serverSettings;\n const response = await __1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n return data;\n }\n /**\n * Get an encoded download url given a file path.\n *\n * @param localPath - An absolute POSIX file path on the server.\n *\n * #### Notes\n * It is expected that the path contains no relative paths.\n *\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(localPath) {\n const baseUrl = this.serverSettings.baseUrl;\n let url = coreutils_1.URLExt.join(baseUrl, FILES_URL, coreutils_1.URLExt.encodeParts(localPath));\n const xsrfTokenMatch = document.cookie.match('\\\\b_xsrf=([^;]*)\\\\b');\n if (xsrfTokenMatch) {\n const fullUrl = new URL(url);\n fullUrl.searchParams.append('_xsrf', xsrfTokenMatch[1]);\n url = fullUrl.toString();\n }\n return Promise.resolve(url);\n }\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async newUntitled(options = {}) {\n var _a;\n let body = '{}';\n if (options) {\n if (options.ext) {\n options.ext = Private.normalizeExtension(options.ext);\n }\n body = JSON.stringify(options);\n }\n const settings = this.serverSettings;\n const url = this._getUrl((_a = options.path) !== null && _a !== void 0 ? _a : '');\n const init = {\n method: 'POST',\n body\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n /**\n * Delete a file.\n *\n * @param localPath - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async delete(localPath) {\n const url = this._getUrl(localPath);\n const settings = this.serverSettings;\n const init = { method: 'DELETE' };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n // TODO: update IPEP27 to specify errors more precisely, so\n // that error types can be detected here with certainty.\n if (response.status !== 204) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._fileChanged.emit({\n type: 'delete',\n oldValue: { path: localPath },\n newValue: null\n });\n }\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file contents model when\n * the file is renamed.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async rename(oldLocalPath, newLocalPath) {\n const settings = this.serverSettings;\n const url = this._getUrl(oldLocalPath);\n const init = {\n method: 'PATCH',\n body: JSON.stringify({ path: newLocalPath })\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'rename',\n oldValue: { path: oldLocalPath },\n newValue: data\n });\n return data;\n }\n /**\n * Save a file.\n *\n * @param localPath - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n *\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async save(localPath, options = {}) {\n const settings = this.serverSettings;\n const url = this._getUrl(localPath);\n const init = {\n method: 'PUT',\n body: JSON.stringify(options)\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n // will return 200 for an existing file and 201 for a new file\n if (response.status !== 200 && response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'save',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n /**\n * Copy a file into a given directory.\n *\n * @param localPath - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n *\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async copy(fromFile, toDir) {\n const settings = this.serverSettings;\n const url = this._getUrl(toDir);\n const init = {\n method: 'POST',\n body: JSON.stringify({ copy_from: fromFile })\n };\n const response = await __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n /**\n * Create a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async createCheckpoint(localPath) {\n const url = this._getUrl(localPath, 'checkpoints');\n const init = { method: 'POST' };\n const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);\n if (response.status !== 201) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateCheckpointModel(data);\n return data;\n }\n /**\n * List available checkpoints for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async listCheckpoints(localPath) {\n const url = this._getUrl(localPath, 'checkpoints');\n const response = await __1.ServerConnection.makeRequest(url, {}, this.serverSettings);\n if (response.status !== 200) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid Checkpoint list');\n }\n for (let i = 0; i < data.length; i++) {\n validate.validateCheckpointModel(data[i]);\n }\n return data;\n }\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async restoreCheckpoint(localPath, checkpointID) {\n const url = this._getUrl(localPath, 'checkpoints', checkpointID);\n const init = { method: 'POST' };\n const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);\n if (response.status !== 204) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n }\n /**\n * Delete a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async deleteCheckpoint(localPath, checkpointID) {\n const url = this._getUrl(localPath, 'checkpoints', checkpointID);\n const init = { method: 'DELETE' };\n const response = await __1.ServerConnection.makeRequest(url, init, this.serverSettings);\n if (response.status !== 204) {\n const err = await __1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n }\n /**\n * Get a REST url for a file given a path.\n */\n _getUrl(...args) {\n const parts = args.map(path => coreutils_1.URLExt.encodeParts(path));\n const baseUrl = this.serverSettings.baseUrl;\n return coreutils_1.URLExt.join(baseUrl, this._apiEndpoint, ...parts);\n }\n}\nexports.Drive = Drive;\n/**\n * A namespace for module private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * Adds a leading dot if not present and converts to lower case.\n */\n function normalizeExtension(extension) {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n Private.normalizeExtension = normalizeExtension;\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateCheckpointModel = exports.validateContentsModel = void 0;\nconst validate_1 = require(\"../validate\");\n/**\n * Validate an `Contents.IModel` object.\n */\nfunction validateContentsModel(model) {\n (0, validate_1.validateProperty)(model, 'name', 'string');\n (0, validate_1.validateProperty)(model, 'path', 'string');\n (0, validate_1.validateProperty)(model, 'type', 'string');\n (0, validate_1.validateProperty)(model, 'created', 'string');\n (0, validate_1.validateProperty)(model, 'last_modified', 'string');\n (0, validate_1.validateProperty)(model, 'mimetype', 'object');\n (0, validate_1.validateProperty)(model, 'content', 'object');\n (0, validate_1.validateProperty)(model, 'format', 'object');\n}\nexports.validateContentsModel = validateContentsModel;\n/**\n * Validate an `Contents.ICheckpointModel` object.\n */\nfunction validateCheckpointModel(model) {\n (0, validate_1.validateProperty)(model, 'id', 'string');\n (0, validate_1.validateProperty)(model, 'last_modified', 'string');\n}\nexports.validateCheckpointModel = validateCheckpointModel;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.EventManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the jupyter-server events service.\n */\nconst SERVICE_EVENTS_URL = 'api/events';\n/**\n * The events API service manager.\n */\nclass EventManager {\n /**\n * Create a new event manager.\n */\n constructor(options = {}) {\n var _a;\n this._socket = null;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n // If subscription fails, the poll attempts to reconnect and backs off.\n this._poll = new polling_1.Poll({ factory: () => this._subscribe() });\n this._stream = new signaling_1.Stream(this);\n // Subscribe to the events socket.\n void this._poll.start();\n }\n /**\n * Whether the event manager is disposed.\n */\n get isDisposed() {\n return this._poll.isDisposed;\n }\n /**\n * An event stream that emits and yields each new event.\n */\n get stream() {\n return this._stream;\n }\n /**\n * Dispose the event manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n // Clean up poll.\n this._poll.dispose();\n // Clean up socket.\n const socket = this._socket;\n if (socket) {\n this._socket = null;\n socket.onopen = () => undefined;\n socket.onerror = () => undefined;\n socket.onmessage = () => undefined;\n socket.onclose = () => undefined;\n socket.close();\n }\n // Clean up stream.\n signaling_1.Signal.clearData(this);\n this._stream.stop();\n }\n /**\n * Post an event request to be emitted by the event bus.\n */\n async emit(event) {\n const { serverSettings } = this;\n const { baseUrl, token } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const url = coreutils_1.URLExt.join(baseUrl, SERVICE_EVENTS_URL) +\n (token ? `?token=${token}` : '');\n const init = { body: JSON.stringify(event), method: 'POST' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n throw new ResponseError(response);\n }\n }\n /**\n * Subscribe to event bus emissions.\n */\n _subscribe() {\n return new Promise((_, reject) => {\n if (this.isDisposed) {\n return;\n }\n const { token, WebSocket, wsUrl } = this.serverSettings;\n const url = coreutils_1.URLExt.join(wsUrl, SERVICE_EVENTS_URL, 'subscribe') +\n (token ? `?token=${encodeURIComponent(token)}` : '');\n const socket = (this._socket = new WebSocket(url));\n const stream = this._stream;\n socket.onclose = () => reject(new Error('EventManager socket closed'));\n socket.onmessage = msg => msg.data && stream.emit(JSON.parse(msg.data));\n });\n }\n}\nexports.EventManager = EventManager;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module services\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./basemanager\"), exports);\n__exportStar(require(\"./config\"), exports);\n__exportStar(require(\"./contents\"), exports);\n__exportStar(require(\"./event\"), exports);\n__exportStar(require(\"./kernel\"), exports);\n__exportStar(require(\"./kernelspec\"), exports);\n__exportStar(require(\"./manager\"), exports);\n__exportStar(require(\"./serverconnection\"), exports);\n__exportStar(require(\"./session\"), exports);\n__exportStar(require(\"./setting\"), exports);\n__exportStar(require(\"./terminal\"), exports);\n__exportStar(require(\"./user\"), exports);\n__exportStar(require(\"./workspace\"), exports);\n__exportStar(require(\"./nbconvert\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CommHandler = void 0;\nconst disposable_1 = require(\"@lumino/disposable\");\nconst KernelMessage = __importStar(require(\"./messages\"));\n/**\n * Comm channel handler.\n */\nclass CommHandler extends disposable_1.DisposableDelegate {\n /**\n * Construct a new comm channel.\n */\n constructor(target, id, kernel, disposeCb) {\n super(disposeCb);\n this._target = '';\n this._id = '';\n this._id = id;\n this._target = target;\n this._kernel = kernel;\n }\n /**\n * The unique id for the comm channel.\n */\n get commId() {\n return this._id;\n }\n /**\n * The target name for the comm channel.\n */\n get targetName() {\n return this._target;\n }\n /**\n * Get the callback for a comm close event.\n *\n * #### Notes\n * This is called when the comm is closed from either the server or client.\n *\n * **See also:** [[ICommClose]], [[close]]\n */\n get onClose() {\n return this._onClose;\n }\n /**\n * Set the callback for a comm close event.\n *\n * #### Notes\n * This is called when the comm is closed from either the server or client. If\n * the function returns a promise, and the kernel was closed from the server,\n * kernel message processing will pause until the returned promise is\n * fulfilled.\n *\n * **See also:** [[close]]\n */\n set onClose(cb) {\n this._onClose = cb;\n }\n /**\n * Get the callback for a comm message received event.\n */\n get onMsg() {\n return this._onMsg;\n }\n /**\n * Set the callback for a comm message received event.\n *\n * #### Notes\n * This is called when a comm message is received. If the function returns a\n * promise, kernel message processing will pause until it is fulfilled.\n */\n set onMsg(cb) {\n this._onMsg = cb;\n }\n /**\n * Open a comm with optional data and metadata.\n *\n * #### Notes\n * This sends a `comm_open` message to the server.\n *\n * **See also:** [[ICommOpen]]\n */\n open(data, metadata, buffers = []) {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot open');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_open',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n target_name: this._target,\n data: data !== null && data !== void 0 ? data : {}\n },\n metadata,\n buffers\n });\n return this._kernel.sendShellMessage(msg, false, true);\n }\n /**\n * Send a `comm_msg` message to the kernel.\n *\n * #### Notes\n * This is a no-op if the comm has been closed.\n *\n * **See also:** [[ICommMsg]]\n */\n send(data, metadata, buffers = [], disposeOnDone = true) {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot send');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_msg',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data\n },\n metadata,\n buffers\n });\n return this._kernel.sendShellMessage(msg, false, disposeOnDone);\n }\n /**\n * Close the comm.\n *\n * #### Notes\n * This will send a `comm_close` message to the kernel, and call the\n * `onClose` callback if set.\n *\n * This is a no-op if the comm is already closed.\n *\n * **See also:** [[ICommClose]], [[onClose]]\n */\n close(data, metadata, buffers = []) {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot close');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_close',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data !== null && data !== void 0 ? data : {}\n },\n metadata,\n buffers\n });\n const future = this._kernel.sendShellMessage(msg, false, true);\n const onClose = this._onClose;\n if (onClose) {\n const ioMsg = KernelMessage.createMessage({\n msgType: 'comm_close',\n channel: 'iopub',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data !== null && data !== void 0 ? data : {}\n },\n metadata,\n buffers\n });\n // In the future, we may want to communicate back to the user the possible\n // promise returned from onClose.\n void onClose(ioMsg);\n }\n this.dispose();\n return future;\n }\n}\nexports.CommHandler = CommHandler;\n//# sourceMappingURL=comm.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelConnection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst comm_1 = require(\"./comm\");\nconst KernelMessage = __importStar(require(\"./messages\"));\nconst future_1 = require(\"./future\");\nconst serialize_1 = require(\"./serialize\");\nconst validate = __importStar(require(\"./validate\"));\nconst kernelspec_1 = require(\"../kernelspec\");\nconst restapi = __importStar(require(\"./restapi\"));\nconst KERNEL_INFO_TIMEOUT = 3000;\nconst RESTARTING_KERNEL_SESSION = '_RESTARTING_';\nconst STARTING_KERNEL_SESSION = '';\n/**\n * Implementation of the Kernel object.\n *\n * #### Notes\n * Messages from the server are handled in the order they were received and\n * asynchronously. Any message handler can return a promise, and message\n * handling will pause until the promise is fulfilled.\n */\nclass KernelConnection {\n /**\n * Construct a kernel object.\n */\n constructor(options) {\n var _a, _b, _c, _d;\n /**\n * Create the kernel websocket connection and add socket status handlers.\n */\n this._createSocket = (useProtocols = true) => {\n this._errorIfDisposed();\n // Make sure the socket is clear\n this._clearSocket();\n // Update the connection status to reflect opening a new connection.\n this._updateConnectionStatus('connecting');\n const settings = this.serverSettings;\n const partialUrl = coreutils_1.URLExt.join(settings.wsUrl, restapi.KERNEL_SERVICE_URL, encodeURIComponent(this._id));\n // Strip any authentication from the display string.\n const display = partialUrl.replace(/^((?:\\w+:)?\\/\\/)(?:[^@\\/]+@)/, '$1');\n console.debug(`Starting WebSocket: ${display}`);\n let url = coreutils_1.URLExt.join(partialUrl, 'channels?session_id=' + encodeURIComponent(this._clientId));\n // If token authentication is in use.\n const token = settings.token;\n if (settings.appendToken && token !== '') {\n url = url + `&token=${encodeURIComponent(token)}`;\n }\n // Try opening the websocket with our list of subprotocols.\n // If the server doesn't handle subprotocols,\n // the accepted protocol will be ''.\n // But we cannot send '' as a subprotocol, so if connection fails,\n // reconnect without subprotocols.\n const supportedProtocols = useProtocols ? this._supportedProtocols : [];\n this._ws = new settings.WebSocket(url, supportedProtocols);\n // Ensure incoming binary messages are not Blobs\n this._ws.binaryType = 'arraybuffer';\n let alreadyCalledOnclose = false;\n const getKernelModel = async (evt) => {\n var _a, _b;\n if (this._isDisposed) {\n return;\n }\n this._reason = '';\n this._model = undefined;\n try {\n const model = await restapi.getKernelModel(this._id, settings);\n this._model = model;\n if ((model === null || model === void 0 ? void 0 : model.execution_state) === 'dead') {\n this._updateStatus('dead');\n }\n else {\n this._onWSClose(evt);\n }\n }\n catch (err) {\n // Try again, if there is a network failure\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof __1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n const timeout = Private.getRandomIntInclusive(10, 30) * 1e3;\n setTimeout(getKernelModel, timeout, evt);\n }\n else {\n this._reason = 'Kernel died unexpectedly';\n this._updateStatus('dead');\n }\n }\n return;\n };\n const earlyClose = async (evt) => {\n // If the websocket was closed early, that could mean\n // that the kernel is actually dead. Try getting\n // information about the kernel from the API call,\n // if that fails, then assume the kernel is dead,\n // otherwise just follow the typical websocket closed\n // protocol.\n if (alreadyCalledOnclose) {\n return;\n }\n alreadyCalledOnclose = true;\n await getKernelModel(evt);\n return;\n };\n this._ws.onmessage = this._onWSMessage;\n this._ws.onopen = this._onWSOpen;\n this._ws.onclose = earlyClose;\n this._ws.onerror = earlyClose;\n };\n // Make websocket callbacks arrow functions so they bind `this`.\n /**\n * Handle a websocket open event.\n */\n this._onWSOpen = (evt) => {\n if (this._ws.protocol !== '' &&\n !this._supportedProtocols.includes(this._ws.protocol)) {\n console.log('Server selected unknown kernel wire protocol:', this._ws.protocol);\n this._updateStatus('dead');\n throw new Error(`Unknown kernel wire protocol: ${this._ws.protocol}`);\n }\n // Remember the kernel wire protocol selected by the server.\n this._selectedProtocol = this._ws.protocol;\n this._ws.onclose = this._onWSClose;\n this._ws.onerror = this._onWSClose;\n this._updateConnectionStatus('connected');\n };\n /**\n * Handle a websocket message, validating and routing appropriately.\n */\n this._onWSMessage = (evt) => {\n // Notify immediately if there is an error with the message.\n let msg;\n try {\n msg = (0, serialize_1.deserialize)(evt.data, this._ws.protocol);\n validate.validateMessage(msg);\n }\n catch (error) {\n error.message = `Kernel message validation error: ${error.message}`;\n // We throw the error so that it bubbles up to the top, and displays the right stack.\n throw error;\n }\n // Update the current kernel session id\n this._kernelSession = msg.header.session;\n // Handle the message asynchronously, in the order received.\n this._msgChain = this._msgChain\n .then(() => {\n // Return so that any promises from handling a message are fulfilled\n // before proceeding to the next message.\n return this._handleMessage(msg);\n })\n .catch(error => {\n // Log any errors in handling the message, thus resetting the _msgChain\n // promise so we can process more messages.\n // Ignore the \"Canceled\" errors that are thrown during kernel dispose.\n if (error.message.startsWith('Canceled future for ')) {\n console.error(error);\n }\n });\n // Emit the message receive signal\n this._anyMessage.emit({ msg, direction: 'recv' });\n };\n /**\n * Handle a websocket close event.\n */\n this._onWSClose = (evt) => {\n if (!this.isDisposed) {\n this._reconnect();\n }\n };\n this._id = '';\n this._name = '';\n this._status = 'unknown';\n this._connectionStatus = 'connecting';\n this._kernelSession = '';\n this._isDisposed = false;\n /**\n * Websocket to communicate with kernel.\n */\n this._ws = null;\n this._username = '';\n this._reconnectLimit = 7;\n this._reconnectAttempt = 0;\n this._reconnectTimeout = null;\n this._supportedProtocols = Object.values(KernelMessage.supportedKernelWebSocketProtocols);\n this._selectedProtocol = '';\n this._futures = new Map();\n this._comms = new Map();\n this._targetRegistry = Object.create(null);\n this._info = new coreutils_2.PromiseDelegate();\n this._pendingMessages = [];\n this._statusChanged = new signaling_1.Signal(this);\n this._connectionStatusChanged = new signaling_1.Signal(this);\n this._disposed = new signaling_1.Signal(this);\n this._iopubMessage = new signaling_1.Signal(this);\n this._anyMessage = new signaling_1.Signal(this);\n this._pendingInput = new signaling_1.Signal(this);\n this._unhandledMessage = new signaling_1.Signal(this);\n this._displayIdToParentIds = new Map();\n this._msgIdToDisplayIds = new Map();\n this._msgChain = Promise.resolve();\n this._hasPendingInput = false;\n this._reason = '';\n this._noOp = () => {\n /* no-op */\n };\n this._name = options.model.name;\n this._id = options.model.id;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings();\n this._clientId = (_b = options.clientId) !== null && _b !== void 0 ? _b : coreutils_2.UUID.uuid4();\n this._username = (_c = options.username) !== null && _c !== void 0 ? _c : '';\n this.handleComms = (_d = options.handleComms) !== null && _d !== void 0 ? _d : true;\n this._createSocket();\n }\n get disposed() {\n return this._disposed;\n }\n /**\n * A signal emitted when the kernel status changes.\n */\n get statusChanged() {\n return this._statusChanged;\n }\n /**\n * A signal emitted when the kernel status changes.\n */\n get connectionStatusChanged() {\n return this._connectionStatusChanged;\n }\n /**\n * A signal emitted for iopub kernel messages.\n *\n * #### Notes\n * This signal is emitted after the iopub message is handled asynchronously.\n */\n get iopubMessage() {\n return this._iopubMessage;\n }\n /**\n * A signal emitted for unhandled kernel message.\n *\n * #### Notes\n * This signal is emitted for a message that was not handled. It is emitted\n * during the asynchronous message handling code.\n */\n get unhandledMessage() {\n return this._unhandledMessage;\n }\n /**\n * The kernel model\n */\n get model() {\n return (this._model || {\n id: this.id,\n name: this.name,\n reason: this._reason\n });\n }\n /**\n * A signal emitted for any kernel message.\n *\n * #### Notes\n * This signal is emitted when a message is received, before it is handled\n * asynchronously.\n *\n * This message is emitted when a message is queued for sending (either in\n * the websocket buffer, or our own pending message buffer). The message may\n * actually be sent across the wire at a later time.\n *\n * The message emitted in this signal should not be modified in any way.\n */\n get anyMessage() {\n return this._anyMessage;\n }\n /**\n * A signal emitted when a kernel has pending inputs from the user.\n */\n get pendingInput() {\n return this._pendingInput;\n }\n /**\n * The id of the server-side kernel.\n */\n get id() {\n return this._id;\n }\n /**\n * The name of the server-side kernel.\n */\n get name() {\n return this._name;\n }\n /**\n * The client username.\n */\n get username() {\n return this._username;\n }\n /**\n * The client unique id.\n */\n get clientId() {\n return this._clientId;\n }\n /**\n * The current status of the kernel.\n */\n get status() {\n return this._status;\n }\n /**\n * The current connection status of the kernel connection.\n */\n get connectionStatus() {\n return this._connectionStatus;\n }\n /**\n * Test whether the kernel has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * The cached kernel info.\n *\n * @returns A promise that resolves to the kernel info.\n */\n get info() {\n return this._info.promise;\n }\n /**\n * The kernel spec.\n *\n * @returns A promise that resolves to the kernel spec.\n */\n get spec() {\n if (this._specPromise) {\n return this._specPromise;\n }\n this._specPromise = kernelspec_1.KernelSpecAPI.getSpecs(this.serverSettings).then(specs => {\n return specs.kernelspecs[this._name];\n });\n return this._specPromise;\n }\n /**\n * Clone the current kernel with a new clientId.\n */\n clone(options = {}) {\n return new KernelConnection({\n model: this.model,\n username: this.username,\n serverSettings: this.serverSettings,\n // handleComms defaults to false since that is safer\n handleComms: false,\n ...options\n });\n }\n /**\n * Dispose of the resources held by the kernel.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n this._updateConnectionStatus('disconnected');\n this._clearKernelState();\n this._pendingMessages = [];\n this._clearSocket();\n // Clear Lumino signals\n signaling_1.Signal.clearData(this);\n }\n /**\n * Send a shell message to the kernel.\n *\n * #### Notes\n * Send a message to the kernel's shell channel, yielding a future object\n * for accepting replies.\n *\n * If `expectReply` is given and `true`, the future is disposed when both a\n * shell reply and an idle status message are received. If `expectReply`\n * is not given or is `false`, the future is resolved when an idle status\n * message is received.\n * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.\n * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.\n *\n * All replies are validated as valid kernel messages.\n *\n * If the kernel status is `dead`, this will throw an error.\n */\n sendShellMessage(msg, expectReply = false, disposeOnDone = true) {\n return this._sendKernelShellControl(future_1.KernelShellFutureHandler, msg, expectReply, disposeOnDone);\n }\n /**\n * Send a control message to the kernel.\n *\n * #### Notes\n * Send a message to the kernel's control channel, yielding a future object\n * for accepting replies.\n *\n * If `expectReply` is given and `true`, the future is disposed when both a\n * control reply and an idle status message are received. If `expectReply`\n * is not given or is `false`, the future is resolved when an idle status\n * message is received.\n * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.\n * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.\n *\n * All replies are validated as valid kernel messages.\n *\n * If the kernel status is `dead`, this will throw an error.\n */\n sendControlMessage(msg, expectReply = false, disposeOnDone = true) {\n return this._sendKernelShellControl(future_1.KernelControlFutureHandler, msg, expectReply, disposeOnDone);\n }\n _sendKernelShellControl(ctor, msg, expectReply = false, disposeOnDone = true) {\n this._sendMessage(msg);\n this._anyMessage.emit({ msg, direction: 'send' });\n const future = new ctor(() => {\n const msgId = msg.header.msg_id;\n this._futures.delete(msgId);\n // Remove stored display id information.\n const displayIds = this._msgIdToDisplayIds.get(msgId);\n if (!displayIds) {\n return;\n }\n displayIds.forEach(displayId => {\n const msgIds = this._displayIdToParentIds.get(displayId);\n if (msgIds) {\n const idx = msgIds.indexOf(msgId);\n if (idx === -1) {\n return;\n }\n if (msgIds.length === 1) {\n this._displayIdToParentIds.delete(displayId);\n }\n else {\n msgIds.splice(idx, 1);\n this._displayIdToParentIds.set(displayId, msgIds);\n }\n }\n });\n this._msgIdToDisplayIds.delete(msgId);\n }, msg, expectReply, disposeOnDone, this);\n this._futures.set(msg.header.msg_id, future);\n return future;\n }\n /**\n * Send a message on the websocket.\n *\n * If queue is true, queue the message for later sending if we cannot send\n * now. Otherwise throw an error.\n *\n * #### Notes\n * As an exception to the queueing, if we are sending a kernel_info_request\n * message while we think the kernel is restarting, we send the message\n * immediately without queueing. This is so that we can trigger a message\n * back, which will then clear the kernel restarting state.\n */\n _sendMessage(msg, queue = true) {\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n // If we have a kernel_info_request and we are starting or restarting, send the\n // kernel_info_request immediately if we can, and if not throw an error so\n // we can retry later. On restarting we do this because we must get at least one message\n // from the kernel to reset the kernel session (thus clearing the restart\n // status sentinel).\n if ((this._kernelSession === STARTING_KERNEL_SESSION ||\n this._kernelSession === RESTARTING_KERNEL_SESSION) &&\n KernelMessage.isInfoRequestMsg(msg)) {\n if (this.connectionStatus === 'connected') {\n this._ws.send((0, serialize_1.serialize)(msg, this._ws.protocol));\n return;\n }\n else {\n throw new Error('Could not send message: status is not connected');\n }\n }\n // If there are pending messages, add to the queue so we keep messages in order\n if (queue && this._pendingMessages.length > 0) {\n this._pendingMessages.push(msg);\n return;\n }\n // Send if the ws allows it, otherwise queue the message.\n if (this.connectionStatus === 'connected' &&\n this._kernelSession !== RESTARTING_KERNEL_SESSION) {\n this._ws.send((0, serialize_1.serialize)(msg, this._ws.protocol));\n }\n else if (queue) {\n this._pendingMessages.push(msg);\n }\n else {\n throw new Error('Could not send message');\n }\n }\n /**\n * Interrupt a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * It is assumed that the API call does not mutate the kernel id or name.\n *\n * The promise will be rejected if the kernel status is `Dead` or if the\n * request fails or the response is invalid.\n */\n async interrupt() {\n this.hasPendingInput = false;\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n return restapi.interruptKernel(this.id, this.serverSettings);\n }\n /**\n * Request a kernel restart.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels)\n * and validates the response model.\n *\n * Any existing Future or Comm objects are cleared once the kernel has\n * actually be restarted.\n *\n * The promise is fulfilled on a valid server response (after the kernel restarts)\n * and rejected otherwise.\n *\n * It is assumed that the API call does not mutate the kernel id or name.\n *\n * The promise will be rejected if the request fails or the response is\n * invalid.\n */\n async restart() {\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n this._updateStatus('restarting');\n this._clearKernelState();\n this._kernelSession = RESTARTING_KERNEL_SESSION;\n await restapi.restartKernel(this.id, this.serverSettings);\n // Reconnect to the kernel to address cases where kernel ports\n // have changed during the restart.\n await this.reconnect();\n this.hasPendingInput = false;\n }\n /**\n * Reconnect to a kernel.\n *\n * #### Notes\n * This may try multiple times to reconnect to a kernel, and will sever any\n * existing connection.\n */\n reconnect() {\n this._errorIfDisposed();\n const result = new coreutils_2.PromiseDelegate();\n // Set up a listener for the connection status changing, which accepts or\n // rejects after the retries are done.\n const fulfill = (sender, status) => {\n if (status === 'connected') {\n result.resolve();\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n else if (status === 'disconnected') {\n result.reject(new Error('Kernel connection disconnected'));\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n };\n this.connectionStatusChanged.connect(fulfill, this);\n // Reset the reconnect limit so we start the connection attempts fresh\n this._reconnectAttempt = 0;\n // Start the reconnection process, which will also clear any existing\n // connection.\n this._reconnect();\n // Return the promise that should resolve on connection or reject if the\n // retries don't work.\n return result.promise;\n }\n /**\n * Shutdown a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * On a valid response, disposes this kernel connection.\n *\n * If the kernel is already `dead`, disposes this kernel connection without\n * a server request.\n */\n async shutdown() {\n if (this.status !== 'dead') {\n await restapi.shutdownKernel(this.id, this.serverSettings);\n }\n this.handleShutdown();\n }\n /**\n * Handles a kernel shutdown.\n *\n * #### Notes\n * This method should be called if we know from outside information that a\n * kernel is dead (for example, we cannot find the kernel model on the\n * server).\n */\n handleShutdown() {\n this._updateStatus('dead');\n this.dispose();\n }\n /**\n * Send a `kernel_info_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n *\n * Fulfills with the `kernel_info_response` content when the shell reply is\n * received and validated.\n */\n async requestKernelInfo() {\n const msg = KernelMessage.createMessage({\n msgType: 'kernel_info_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content: {}\n });\n let reply;\n try {\n reply = (await Private.handleShellMessage(this, msg));\n }\n catch (e) {\n // If we rejected because the future was disposed, ignore and return.\n if (this.isDisposed) {\n return;\n }\n else {\n throw e;\n }\n }\n this._errorIfDisposed();\n if (!reply) {\n return;\n }\n // Kernels sometimes do not include a status field on kernel_info_reply\n // messages, so set a default for now.\n // See https://github.com/jupyterlab/jupyterlab/issues/6760\n if (reply.content.status === undefined) {\n reply.content.status = 'ok';\n }\n if (reply.content.status !== 'ok') {\n this._info.reject('Kernel info reply errored');\n return reply;\n }\n this._info.resolve(reply.content);\n this._kernelSession = reply.header.session;\n return reply;\n }\n /**\n * Send a `complete_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).\n *\n * Fulfills with the `complete_reply` content when the shell reply is\n * received and validated.\n */\n requestComplete(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'complete_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send an `inspect_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).\n *\n * Fulfills with the `inspect_reply` content when the shell reply is\n * received and validated.\n */\n requestInspect(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'inspect_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content: content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send a `history_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * Fulfills with the `history_reply` content when the shell reply is\n * received and validated.\n */\n requestHistory(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'history_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send an `execute_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).\n *\n * Future `onReply` is called with the `execute_reply` content when the\n * shell reply is received and validated. The future will resolve when\n * this message is received and the `idle` iopub status is received.\n * The future will also be disposed at this point unless `disposeOnDone`\n * is specified and `false`, in which case it is up to the caller to dispose\n * of the future.\n *\n * **See also:** [[IExecuteReply]]\n */\n requestExecute(content, disposeOnDone = true, metadata) {\n const defaults = {\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: true,\n stop_on_error: false\n };\n const msg = KernelMessage.createMessage({\n msgType: 'execute_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content: { ...defaults, ...content },\n metadata\n });\n return this.sendShellMessage(msg, true, disposeOnDone);\n }\n /**\n * Send an experimental `debug_request` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\n requestDebug(content, disposeOnDone = true) {\n const msg = KernelMessage.createMessage({\n msgType: 'debug_request',\n channel: 'control',\n username: this._username,\n session: this._clientId,\n content\n });\n return this.sendControlMessage(msg, true, disposeOnDone);\n }\n /**\n * Send an `is_complete_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).\n *\n * Fulfills with the `is_complete_response` content when the shell reply is\n * received and validated.\n */\n requestIsComplete(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'is_complete_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send a `comm_info_request` message.\n *\n * #### Notes\n * Fulfills with the `comm_info_reply` content when the shell reply is\n * received and validated.\n */\n requestCommInfo(content) {\n const msg = KernelMessage.createMessage({\n msgType: 'comm_info_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n content\n });\n return Private.handleShellMessage(this, msg);\n }\n /**\n * Send an `input_reply` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).\n */\n sendInputReply(content, parent_header) {\n const msg = KernelMessage.createMessage({\n msgType: 'input_reply',\n channel: 'stdin',\n username: this._username,\n session: this._clientId,\n content\n });\n msg.parent_header = parent_header;\n this._sendMessage(msg);\n this._anyMessage.emit({ msg, direction: 'send' });\n this.hasPendingInput = false;\n }\n /**\n * Create a new comm.\n *\n * #### Notes\n * If a client-side comm already exists with the given commId, an error is thrown.\n * If the kernel does not handle comms, an error is thrown.\n */\n createComm(targetName, commId = coreutils_2.UUID.uuid4()) {\n if (!this.handleComms) {\n throw new Error('Comms are disabled on this kernel connection');\n }\n if (this._comms.has(commId)) {\n throw new Error('Comm is already created');\n }\n const comm = new comm_1.CommHandler(targetName, commId, this, () => {\n this._unregisterComm(commId);\n });\n this._comms.set(commId, comm);\n return comm;\n }\n /**\n * Check if a comm exists.\n */\n hasComm(commId) {\n return this._comms.has(commId);\n }\n /**\n * Register a comm target handler.\n *\n * @param targetName - The name of the comm target.\n *\n * @param callback - The callback invoked for a comm open message.\n *\n * @returns A disposable used to unregister the comm target.\n *\n * #### Notes\n * Only one comm target can be registered to a target name at a time, an\n * existing callback for the same target name will be overridden. A registered\n * comm target handler will take precedence over a comm which specifies a\n * `target_module`.\n *\n * If the callback returns a promise, kernel message processing will pause\n * until the returned promise is fulfilled.\n */\n registerCommTarget(targetName, callback) {\n if (!this.handleComms) {\n return;\n }\n this._targetRegistry[targetName] = callback;\n }\n /**\n * Remove a comm target handler.\n *\n * @param targetName - The name of the comm target to remove.\n *\n * @param callback - The callback to remove.\n *\n * #### Notes\n * The comm target is only removed if the callback argument matches.\n */\n removeCommTarget(targetName, callback) {\n if (!this.handleComms) {\n return;\n }\n if (!this.isDisposed && this._targetRegistry[targetName] === callback) {\n delete this._targetRegistry[targetName];\n }\n }\n /**\n * Register an IOPub message hook.\n *\n * @param msg_id - The parent_header message id the hook will intercept.\n *\n * @param hook - The callback invoked for the message.\n *\n * #### Notes\n * The IOPub hook system allows you to preempt the handlers for IOPub\n * messages that are responses to a given message id.\n *\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case all kernel message\n * processing pauses until the promise is fulfilled. If a hook return value\n * resolves to false, any later hooks will not run and the function will\n * return a promise resolving to false. If a hook throws an error, the error\n * is logged to the console and the next hook is run. If a hook is\n * registered during the hook processing, it will not run until the next\n * message. If a hook is removed during the hook processing, it will be\n * deactivated immediately.\n *\n * See also [[IFuture.registerMessageHook]].\n */\n registerMessageHook(msgId, hook) {\n var _a;\n const future = (_a = this._futures) === null || _a === void 0 ? void 0 : _a.get(msgId);\n if (future) {\n future.registerMessageHook(hook);\n }\n }\n /**\n * Remove an IOPub message hook.\n *\n * @param msg_id - The parent_header message id the hook intercepted.\n *\n * @param hook - The callback invoked for the message.\n *\n */\n removeMessageHook(msgId, hook) {\n var _a;\n const future = (_a = this._futures) === null || _a === void 0 ? void 0 : _a.get(msgId);\n if (future) {\n future.removeMessageHook(hook);\n }\n }\n /**\n * Remove the input guard, if any.\n */\n removeInputGuard() {\n this.hasPendingInput = false;\n }\n /**\n * Handle a message with a display id.\n *\n * @returns Whether the message was handled.\n */\n async _handleDisplayId(displayId, msg) {\n var _a, _b;\n const msgId = msg.parent_header.msg_id;\n let parentIds = this._displayIdToParentIds.get(displayId);\n if (parentIds) {\n // We've seen it before, update existing outputs with same display_id\n // by handling display_data as update_display_data.\n const updateMsg = {\n header: coreutils_2.JSONExt.deepCopy(msg.header),\n parent_header: coreutils_2.JSONExt.deepCopy(msg.parent_header),\n metadata: coreutils_2.JSONExt.deepCopy(msg.metadata),\n content: coreutils_2.JSONExt.deepCopy(msg.content),\n channel: msg.channel,\n buffers: msg.buffers ? msg.buffers.slice() : []\n };\n updateMsg.header.msg_type = 'update_display_data';\n await Promise.all(parentIds.map(async (parentId) => {\n const future = this._futures && this._futures.get(parentId);\n if (future) {\n await future.handleMsg(updateMsg);\n }\n }));\n }\n // We're done here if it's update_display.\n if (msg.header.msg_type === 'update_display_data') {\n // It's an update, don't proceed to the normal display.\n return true;\n }\n // Regular display_data with id, record it for future updating\n // in _displayIdToParentIds for future lookup.\n parentIds = (_a = this._displayIdToParentIds.get(displayId)) !== null && _a !== void 0 ? _a : [];\n if (parentIds.indexOf(msgId) === -1) {\n parentIds.push(msgId);\n }\n this._displayIdToParentIds.set(displayId, parentIds);\n // Add to our map of display ids for this message.\n const displayIds = (_b = this._msgIdToDisplayIds.get(msgId)) !== null && _b !== void 0 ? _b : [];\n if (displayIds.indexOf(msgId) === -1) {\n displayIds.push(msgId);\n }\n this._msgIdToDisplayIds.set(msgId, displayIds);\n // Let the message propagate to the intended recipient.\n return false;\n }\n /**\n * Forcefully clear the socket state.\n *\n * #### Notes\n * This will clear all socket state without calling any handlers and will\n * not update the connection status. If you call this method, you are\n * responsible for updating the connection status as needed and recreating\n * the socket if you plan to reconnect.\n */\n _clearSocket() {\n if (this._ws !== null) {\n // Clear the websocket event handlers and the socket itself.\n this._ws.onopen = this._noOp;\n this._ws.onclose = this._noOp;\n this._ws.onerror = this._noOp;\n this._ws.onmessage = this._noOp;\n this._ws.close();\n this._ws = null;\n }\n }\n /**\n * Handle status iopub messages from the kernel.\n */\n _updateStatus(status) {\n if (this._status === status || this._status === 'dead') {\n return;\n }\n this._status = status;\n Private.logKernelStatus(this);\n this._statusChanged.emit(status);\n if (status === 'dead') {\n this.dispose();\n }\n }\n /**\n * Send pending messages to the kernel.\n */\n _sendPending() {\n // We check to make sure we are still connected each time. For\n // example, if a websocket buffer overflows, it may close, so we should\n // stop sending messages.\n while (this.connectionStatus === 'connected' &&\n this._kernelSession !== RESTARTING_KERNEL_SESSION &&\n this._pendingMessages.length > 0) {\n this._sendMessage(this._pendingMessages[0], false);\n // We shift the message off the queue after the message is sent so that\n // if there is an exception, the message is still pending.\n this._pendingMessages.shift();\n }\n }\n /**\n * Clear the internal state.\n */\n _clearKernelState() {\n this._kernelSession = '';\n this._pendingMessages = [];\n this._futures.forEach(future => {\n future.dispose();\n });\n this._comms.forEach(comm => {\n comm.dispose();\n });\n this._msgChain = Promise.resolve();\n this._futures = new Map();\n this._comms = new Map();\n this._displayIdToParentIds.clear();\n this._msgIdToDisplayIds.clear();\n }\n /**\n * Check to make sure it is okay to proceed to handle a message.\n *\n * #### Notes\n * Because we handle messages asynchronously, before a message is handled the\n * kernel might be disposed or restarted (and have a different session id).\n * This function throws an error in each of these cases. This is meant to be\n * called at the start of an asynchronous message handler to cancel message\n * processing if the message no longer is valid.\n */\n _assertCurrentMessage(msg) {\n this._errorIfDisposed();\n if (msg.header.session !== this._kernelSession) {\n throw new Error(`Canceling handling of old message: ${msg.header.msg_type}`);\n }\n }\n /**\n * Handle a `comm_open` kernel message.\n */\n async _handleCommOpen(msg) {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = new comm_1.CommHandler(content.target_name, content.comm_id, this, () => {\n this._unregisterComm(content.comm_id);\n });\n this._comms.set(content.comm_id, comm);\n try {\n const target = await Private.loadObject(content.target_name, content.target_module, this._targetRegistry);\n await target(comm, msg);\n }\n catch (e) {\n // Close the comm asynchronously. We cannot block message processing on\n // kernel messages to wait for another kernel message.\n comm.close();\n console.error('Exception opening new comm');\n throw e;\n }\n }\n /**\n * Handle 'comm_close' kernel message.\n */\n async _handleCommClose(msg) {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = this._comms.get(content.comm_id);\n if (!comm) {\n console.error('Comm not found for comm id ' + content.comm_id);\n return;\n }\n this._unregisterComm(comm.commId);\n const onClose = comm.onClose;\n if (onClose) {\n // tslint:disable-next-line:await-promise\n await onClose(msg);\n }\n comm.dispose();\n }\n /**\n * Handle a 'comm_msg' kernel message.\n */\n async _handleCommMsg(msg) {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = this._comms.get(content.comm_id);\n if (!comm) {\n return;\n }\n const onMsg = comm.onMsg;\n if (onMsg) {\n // tslint:disable-next-line:await-promise\n await onMsg(msg);\n }\n }\n /**\n * Unregister a comm instance.\n */\n _unregisterComm(commId) {\n this._comms.delete(commId);\n }\n /**\n * Handle connection status changes.\n */\n _updateConnectionStatus(connectionStatus) {\n if (this._connectionStatus === connectionStatus) {\n return;\n }\n this._connectionStatus = connectionStatus;\n // If we are not 'connecting', reset any reconnection attempts.\n if (connectionStatus !== 'connecting') {\n this._reconnectAttempt = 0;\n clearTimeout(this._reconnectTimeout);\n }\n if (this.status !== 'dead') {\n if (connectionStatus === 'connected') {\n let restarting = this._kernelSession === RESTARTING_KERNEL_SESSION;\n // Send a kernel info request to make sure we send at least one\n // message to get kernel status back. Always request kernel info\n // first, to get kernel status back and ensure iopub is fully\n // established. If we are restarting, this message will skip the queue\n // and be sent immediately.\n let p = this.requestKernelInfo();\n // Send any pending messages after the kernelInfo resolves, or after a\n // timeout as a failsafe.\n let sendPendingCalled = false;\n let sendPendingOnce = () => {\n if (sendPendingCalled) {\n return;\n }\n sendPendingCalled = true;\n if (restarting && this._kernelSession === RESTARTING_KERNEL_SESSION) {\n // We were restarting and a message didn't arrive to set the\n // session, but we just assume the restart succeeded and send any\n // pending messages.\n // FIXME: it would be better to retry the kernel_info_request here\n this._kernelSession = '';\n }\n clearTimeout(timeoutHandle);\n if (this._pendingMessages.length > 0) {\n this._sendPending();\n }\n };\n void p.then(sendPendingOnce);\n // FIXME: if sent while zmq subscriptions are not established,\n // kernelInfo may not resolve, so use a timeout to ensure we don't hang forever.\n // It may be preferable to retry kernelInfo rather than give up after one timeout.\n let timeoutHandle = setTimeout(sendPendingOnce, KERNEL_INFO_TIMEOUT);\n }\n else {\n // If the connection is down, then we do not know what is happening\n // with the kernel, so set the status to unknown.\n this._updateStatus('unknown');\n }\n }\n // Notify others that the connection status changed.\n this._connectionStatusChanged.emit(connectionStatus);\n }\n async _handleMessage(msg) {\n var _a, _b;\n let handled = false;\n // Check to see if we have a display_id we need to reroute.\n if (msg.parent_header &&\n msg.channel === 'iopub' &&\n (KernelMessage.isDisplayDataMsg(msg) ||\n KernelMessage.isUpdateDisplayDataMsg(msg) ||\n KernelMessage.isExecuteResultMsg(msg))) {\n // display_data messages may re-route based on their display_id.\n const transient = ((_a = msg.content.transient) !== null && _a !== void 0 ? _a : {});\n const displayId = transient['display_id'];\n if (displayId) {\n handled = await this._handleDisplayId(displayId, msg);\n // The await above may make this message out of date, so check again.\n this._assertCurrentMessage(msg);\n }\n }\n if (!handled && msg.parent_header) {\n const parentHeader = msg.parent_header;\n const future = (_b = this._futures) === null || _b === void 0 ? void 0 : _b.get(parentHeader.msg_id);\n if (future) {\n await future.handleMsg(msg);\n this._assertCurrentMessage(msg);\n }\n else {\n // If the message was sent by us and was not iopub, it is orphaned.\n const owned = parentHeader.session === this.clientId;\n if (msg.channel !== 'iopub' && owned) {\n this._unhandledMessage.emit(msg);\n }\n }\n }\n if (msg.channel === 'iopub') {\n switch (msg.header.msg_type) {\n case 'status': {\n // Updating the status is synchronous, and we call no async user code\n const executionState = msg.content\n .execution_state;\n if (executionState === 'restarting') {\n // The kernel has been auto-restarted by the server. After\n // processing for this message is completely done, we want to\n // handle this restart, so we don't await, but instead schedule\n // the work as a microtask (i.e., in a promise resolution). We\n // schedule this here so that it comes before any microtasks that\n // might be scheduled in the status signal emission below.\n void Promise.resolve().then(async () => {\n this._updateStatus('autorestarting');\n this._clearKernelState();\n // We must reconnect since the kernel connection information may have\n // changed, and the server only refreshes its zmq connection when a new\n // websocket is opened.\n await this.reconnect();\n });\n }\n this._updateStatus(executionState);\n break;\n }\n case 'comm_open':\n if (this.handleComms) {\n await this._handleCommOpen(msg);\n }\n break;\n case 'comm_msg':\n if (this.handleComms) {\n await this._handleCommMsg(msg);\n }\n break;\n case 'comm_close':\n if (this.handleComms) {\n await this._handleCommClose(msg);\n }\n break;\n default:\n break;\n }\n // If the message was a status dead message, we might have disposed ourselves.\n if (!this.isDisposed) {\n this._assertCurrentMessage(msg);\n // the message wouldn't be emitted if we were disposed anyway.\n this._iopubMessage.emit(msg);\n }\n }\n }\n /**\n * Attempt a connection if we have not exhausted connection attempts.\n */\n _reconnect() {\n this._errorIfDisposed();\n // Clear any existing reconnection attempt\n clearTimeout(this._reconnectTimeout);\n // Update the connection status and schedule a possible reconnection.\n if (this._reconnectAttempt < this._reconnectLimit) {\n this._updateConnectionStatus('connecting');\n // The first reconnect attempt should happen immediately, and subsequent\n // attempts should pick a random number in a growing range so that we\n // don't overload the server with synchronized reconnection attempts\n // across multiple kernels.\n const timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));\n console.warn(`Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`);\n // Try reconnection with subprotocols if the server had supported them.\n // Otherwise, try reconnection without subprotocols.\n const useProtocols = this._selectedProtocol !== '' ? true : false;\n this._reconnectTimeout = setTimeout(this._createSocket, timeout, useProtocols);\n this._reconnectAttempt += 1;\n }\n else {\n this._updateConnectionStatus('disconnected');\n }\n // Clear the websocket event handlers and the socket itself.\n this._clearSocket();\n }\n /**\n * Utility function to throw an error if this instance is disposed.\n */\n _errorIfDisposed() {\n if (this.isDisposed) {\n throw new Error('Kernel connection is disposed');\n }\n }\n get hasPendingInput() {\n return this._hasPendingInput;\n }\n set hasPendingInput(value) {\n this._hasPendingInput = value;\n this._pendingInput.emit(value);\n }\n}\nexports.KernelConnection = KernelConnection;\n/**\n * A private namespace for the Kernel.\n */\nvar Private;\n(function (Private) {\n /**\n * Log the current kernel status.\n */\n function logKernelStatus(kernel) {\n switch (kernel.status) {\n case 'idle':\n case 'busy':\n case 'unknown':\n return;\n default:\n console.debug(`Kernel: ${kernel.status} (${kernel.id})`);\n break;\n }\n }\n Private.logKernelStatus = logKernelStatus;\n /**\n * Send a kernel message to the kernel and resolve the reply message.\n */\n async function handleShellMessage(kernel, msg) {\n const future = kernel.sendShellMessage(msg, true);\n return future.done;\n }\n Private.handleShellMessage = handleShellMessage;\n /**\n * Try to load an object from a module or a registry.\n *\n * Try to load an object from a module asynchronously if a module\n * is specified, otherwise tries to load an object from the global\n * registry, if the global registry is provided.\n *\n * #### Notes\n * Loading a module uses requirejs.\n */\n function loadObject(name, moduleName, registry) {\n return new Promise((resolve, reject) => {\n // Try loading the module using require.js\n if (moduleName) {\n if (typeof requirejs === 'undefined') {\n throw new Error('requirejs not found');\n }\n requirejs([moduleName], (mod) => {\n if (mod[name] === void 0) {\n const msg = `Object '${name}' not found in module '${moduleName}'`;\n reject(new Error(msg));\n }\n else {\n resolve(mod[name]);\n }\n }, reject);\n }\n else {\n if (registry === null || registry === void 0 ? void 0 : registry[name]) {\n resolve(registry[name]);\n }\n else {\n reject(new Error(`Object '${name}' not found in registry`));\n }\n }\n });\n }\n Private.loadObject = loadObject;\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n Private.getRandomIntInclusive = getRandomIntInclusive;\n})(Private || (Private = {}));\n//# sourceMappingURL=default.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelShellFutureHandler = exports.KernelControlFutureHandler = exports.KernelFutureHandler = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst disposable_1 = require(\"@lumino/disposable\");\nconst KernelMessage = __importStar(require(\"./messages\"));\n/**\n * Implementation of a kernel future.\n *\n * If a reply is expected, the Future is considered done when both a `reply`\n * message and an `idle` iopub status message have been received. Otherwise, it\n * is considered done when the `idle` status is received.\n *\n */\nclass KernelFutureHandler extends disposable_1.DisposableDelegate {\n /**\n * Construct a new KernelFutureHandler.\n */\n constructor(cb, msg, expectReply, disposeOnDone, kernel) {\n super(cb);\n this._status = 0;\n this._stdin = Private.noOp;\n this._iopub = Private.noOp;\n this._reply = Private.noOp;\n this._done = new coreutils_1.PromiseDelegate();\n this._hooks = new Private.HookList();\n this._disposeOnDone = true;\n this._msg = msg;\n if (!expectReply) {\n this._setFlag(Private.KernelFutureFlag.GotReply);\n }\n this._disposeOnDone = disposeOnDone;\n this._kernel = kernel;\n }\n /**\n * Get the original outgoing message.\n */\n get msg() {\n return this._msg;\n }\n /**\n * A promise that resolves when the future is done.\n */\n get done() {\n return this._done.promise;\n }\n /**\n * Get the reply handler.\n */\n get onReply() {\n return this._reply;\n }\n /**\n * Set the reply handler.\n */\n set onReply(cb) {\n this._reply = cb;\n }\n /**\n * Get the iopub handler.\n */\n get onIOPub() {\n return this._iopub;\n }\n /**\n * Set the iopub handler.\n */\n set onIOPub(cb) {\n this._iopub = cb;\n }\n /**\n * Get the stdin handler.\n */\n get onStdin() {\n return this._stdin;\n }\n /**\n * Set the stdin handler.\n */\n set onStdin(cb) {\n this._stdin = cb;\n }\n /**\n * Register hook for IOPub messages.\n *\n * @param hook - The callback invoked for an IOPub message.\n *\n * #### Notes\n * The IOPub hook system allows you to preempt the handlers for IOPub\n * messages handled by the future.\n *\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case all kernel message\n * processing pauses until the promise is fulfilled. If a hook return value\n * resolves to false, any later hooks will not run and the function will\n * return a promise resolving to false. If a hook throws an error, the error\n * is logged to the console and the next hook is run. If a hook is\n * registered during the hook processing, it will not run until the next\n * message. If a hook is removed during the hook processing, it will be\n * deactivated immediately.\n */\n registerMessageHook(hook) {\n if (this.isDisposed) {\n throw new Error('Kernel future is disposed');\n }\n this._hooks.add(hook);\n }\n /**\n * Remove a hook for IOPub messages.\n *\n * @param hook - The hook to remove.\n *\n * #### Notes\n * If a hook is removed during the hook processing, it will be deactivated immediately.\n */\n removeMessageHook(hook) {\n if (this.isDisposed) {\n return;\n }\n this._hooks.remove(hook);\n }\n /**\n * Send an `input_reply` message.\n */\n sendInputReply(content, parent_header) {\n this._kernel.sendInputReply(content, parent_header);\n }\n /**\n * Dispose and unregister the future.\n */\n dispose() {\n this._stdin = Private.noOp;\n this._iopub = Private.noOp;\n this._reply = Private.noOp;\n this._hooks = null;\n if (!this._testFlag(Private.KernelFutureFlag.IsDone)) {\n // TODO: Uncomment the following logging code, and check for any tests that trigger it.\n // let status = [];\n // if (!this._testFlag(Private.KernelFutureFlag.GotIdle)) {\n // status.push('idle');\n // }\n // if (!this._testFlag(Private.KernelFutureFlag.GotReply)) {\n // status.push('reply');\n // }\n // console.warn(\n // `*************** DISPOSED BEFORE DONE: K${this._kernel.id.slice(\n // 0,\n // 6\n // )} M${this._msg.header.msg_id.slice(0, 6)} missing ${status.join(' ')}`\n // );\n // Reject the `done` promise, but catch its error here in case no one else\n // is waiting for the promise to resolve. This prevents the error from\n // being displayed in the console, but does not prevent it from being\n // caught by a client who is waiting for it.\n this._done.promise.catch(() => {\n /* no-op */\n });\n this._done.reject(new Error(`Canceled future for ${this.msg.header.msg_type} message before replies were done`));\n }\n super.dispose();\n }\n /**\n * Handle an incoming kernel message.\n */\n async handleMsg(msg) {\n switch (msg.channel) {\n case 'control':\n case 'shell':\n if (msg.channel === this.msg.channel &&\n msg.parent_header.msg_id === this.msg.header.msg_id) {\n await this._handleReply(msg);\n }\n break;\n case 'stdin':\n await this._handleStdin(msg);\n break;\n case 'iopub':\n await this._handleIOPub(msg);\n break;\n default:\n break;\n }\n }\n async _handleReply(msg) {\n const reply = this._reply;\n if (reply) {\n // tslint:disable-next-line:await-promise\n await reply(msg);\n }\n this._replyMsg = msg;\n this._setFlag(Private.KernelFutureFlag.GotReply);\n if (this._testFlag(Private.KernelFutureFlag.GotIdle)) {\n this._handleDone();\n }\n }\n async _handleStdin(msg) {\n this._kernel.hasPendingInput = true;\n const stdin = this._stdin;\n if (stdin) {\n // tslint:disable-next-line:await-promise\n await stdin(msg);\n }\n }\n async _handleIOPub(msg) {\n const process = await this._hooks.process(msg);\n const iopub = this._iopub;\n if (process && iopub) {\n // tslint:disable-next-line:await-promise\n await iopub(msg);\n }\n if (KernelMessage.isStatusMsg(msg) &&\n msg.content.execution_state === 'idle') {\n this._setFlag(Private.KernelFutureFlag.GotIdle);\n if (this._testFlag(Private.KernelFutureFlag.GotReply)) {\n this._handleDone();\n }\n }\n }\n _handleDone() {\n if (this._testFlag(Private.KernelFutureFlag.IsDone)) {\n return;\n }\n this._setFlag(Private.KernelFutureFlag.IsDone);\n this._done.resolve(this._replyMsg);\n if (this._disposeOnDone) {\n this.dispose();\n }\n }\n /**\n * Test whether the given future flag is set.\n */\n _testFlag(flag) {\n // tslint:disable-next-line\n return (this._status & flag) !== 0;\n }\n /**\n * Set the given future flag.\n */\n _setFlag(flag) {\n // tslint:disable-next-line\n this._status |= flag;\n }\n}\nexports.KernelFutureHandler = KernelFutureHandler;\nclass KernelControlFutureHandler extends KernelFutureHandler {\n}\nexports.KernelControlFutureHandler = KernelControlFutureHandler;\nclass KernelShellFutureHandler extends KernelFutureHandler {\n}\nexports.KernelShellFutureHandler = KernelShellFutureHandler;\nvar Private;\n(function (Private) {\n /**\n * A no-op function.\n */\n Private.noOp = () => {\n /* no-op */\n };\n /**\n * Defer a computation.\n *\n * #### NOTES\n * We can't just use requestAnimationFrame since it is not available in node.\n * This implementation is from Phosphor:\n * https://github.com/phosphorjs/phosphor/blob/e88e4321289bb1198f3098e7bda40736501f2ed8/tests/test-messaging/src/index.spec.ts#L63\n */\n const defer = (() => {\n const ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n class HookList {\n constructor() {\n this._hooks = [];\n }\n /**\n * Register a hook.\n *\n * @param hook - The callback to register.\n */\n add(hook) {\n this.remove(hook);\n this._hooks.push(hook);\n }\n /**\n * Remove a hook, if it exists in the hook list.\n *\n * @param hook - The callback to remove.\n */\n remove(hook) {\n const index = this._hooks.indexOf(hook);\n if (index >= 0) {\n this._hooks[index] = null;\n this._scheduleCompact();\n }\n }\n /**\n * Process a message through the hooks.\n *\n * @returns a promise resolving to false if any hook resolved as false,\n * otherwise true\n *\n * #### Notes\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case processing pauses until\n * the promise is fulfilled. If a hook return value resolves to false, any\n * later hooks will not run and the function will return a promise resolving\n * to false. If a hook throws an error, the error is logged to the console\n * and the next hook is run. If a hook is registered during the hook\n * processing, it will not run until the next message. If a hook is removed\n * during the hook processing, it will be deactivated immediately.\n */\n async process(msg) {\n // Wait until we can start a new process run.\n await this._processing;\n // Start the next process run.\n const processing = new coreutils_1.PromiseDelegate();\n this._processing = processing.promise;\n let continueHandling;\n // Call the end hook (most recently-added) first. Starting at the end also\n // guarantees that hooks added during the processing will not be run in\n // this process run.\n for (let i = this._hooks.length - 1; i >= 0; i--) {\n const hook = this._hooks[i];\n // If the hook has been removed, continue to the next one.\n if (hook === null) {\n continue;\n }\n // Execute the hook and log any errors.\n try {\n // tslint:disable-next-line:await-promise\n continueHandling = await hook(msg);\n }\n catch (err) {\n continueHandling = true;\n console.error(err);\n }\n // If the hook resolved to false, stop processing and return.\n if (continueHandling === false) {\n processing.resolve(undefined);\n return false;\n }\n }\n // All hooks returned true (or errored out), so return true.\n processing.resolve(undefined);\n return true;\n }\n /**\n * Schedule a cleanup of the list, removing any hooks that have been nulled out.\n */\n _scheduleCompact() {\n if (!this._compactScheduled) {\n this._compactScheduled = true;\n // Schedule a compaction in between processing runs. We do the\n // scheduling in an animation frame to rate-limit our compactions. If we\n // need to compact more frequently, we can change this to directly\n // schedule the compaction.\n defer(() => {\n this._processing = this._processing.then(() => {\n this._compactScheduled = false;\n this._compact();\n });\n });\n }\n }\n /**\n * Compact the list, removing any nulls.\n */\n _compact() {\n let numNulls = 0;\n for (let i = 0, len = this._hooks.length; i < len; i++) {\n const hook = this._hooks[i];\n if (this._hooks[i] === null) {\n numNulls++;\n }\n else {\n this._hooks[i - numNulls] = hook;\n }\n }\n this._hooks.length -= numNulls;\n }\n }\n Private.HookList = HookList;\n /**\n * Bit flags for the kernel future state.\n */\n let KernelFutureFlag;\n (function (KernelFutureFlag) {\n KernelFutureFlag[KernelFutureFlag[\"GotReply\"] = 1] = \"GotReply\";\n KernelFutureFlag[KernelFutureFlag[\"GotIdle\"] = 2] = \"GotIdle\";\n KernelFutureFlag[KernelFutureFlag[\"IsDone\"] = 4] = \"IsDone\";\n KernelFutureFlag[KernelFutureFlag[\"DisposeOnDone\"] = 8] = \"DisposeOnDone\";\n })(KernelFutureFlag = Private.KernelFutureFlag || (Private.KernelFutureFlag = {}));\n})(Private || (Private = {}));\n//# sourceMappingURL=future.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelConnection = exports.KernelAPI = exports.KernelMessage = exports.Kernel = void 0;\n// Namespace some of our modules for convenience and backwards compatibility.\nconst Kernel = __importStar(require(\"./kernel\"));\nexports.Kernel = Kernel;\nconst KernelMessage = __importStar(require(\"./messages\"));\nexports.KernelMessage = KernelMessage;\nconst KernelAPI = __importStar(require(\"./restapi\"));\nexports.KernelAPI = KernelAPI;\nconst default_1 = require(\"./default\");\nObject.defineProperty(exports, \"KernelConnection\", { enumerable: true, get: function () { return default_1.KernelConnection; } });\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=kernel.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelManager = void 0;\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst basemanager_1 = require(\"../basemanager\");\nconst restapi_1 = require(\"./restapi\");\nconst default_1 = require(\"./default\");\n/**\n * An implementation of a kernel manager.\n */\nclass KernelManager extends basemanager_1.BaseManager {\n /**\n * Construct a new kernel manager.\n *\n * @param options - The default options for kernel.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n this._kernelConnections = new Set();\n this._models = new Map();\n this._runningChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // Start model and specs polling with exponential backoff.\n this._pollModels = new polling_1.Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:KernelManager#models`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n this._isReady = true;\n })();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * A signal emitted when the running kernels change.\n */\n get runningChanged() {\n return this._runningChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._models.clear();\n this._kernelConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n /**\n * Connect to an existing kernel.\n *\n * @returns The new kernel connection.\n *\n * #### Notes\n * This will use the manager's server settings and ignore any server\n * settings passed in the options.\n */\n connectTo(options) {\n var _a;\n const { id } = options.model;\n let handleComms = (_a = options.handleComms) !== null && _a !== void 0 ? _a : true;\n // By default, handle comms only if no other kernel connection is.\n if (options.handleComms === undefined) {\n for (const kc of this._kernelConnections) {\n if (kc.id === id && kc.handleComms) {\n handleComms = false;\n break;\n }\n }\n }\n const kernelConnection = new default_1.KernelConnection({\n handleComms,\n ...options,\n serverSettings: this.serverSettings\n });\n this._onStarted(kernelConnection);\n if (!this._models.has(id)) {\n // We trust the user to connect to an existing kernel, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return kernelConnection;\n }\n /**\n * Create an iterator over the most recent running kernels.\n *\n * @returns A new iterator over the running kernels.\n */\n running() {\n return this._models.values();\n }\n /**\n * Force a refresh of the running kernels.\n *\n * @returns A promise that resolves when the running list has been refreshed.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n async refreshRunning() {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n /**\n * Start a new kernel.\n *\n * @param createOptions - The kernel creation options\n *\n * @param connectOptions - The kernel connection options\n *\n * @returns A promise that resolves with the kernel connection.\n *\n * #### Notes\n * The manager `serverSettings` will be always be used.\n */\n async startNew(createOptions = {}, connectOptions = {}) {\n const model = await (0, restapi_1.startNew)(createOptions, this.serverSettings);\n return this.connectTo({\n ...connectOptions,\n model\n });\n }\n /**\n * Shut down a kernel by id.\n *\n * @param id - The id of the target kernel.\n *\n * @returns A promise that resolves when the operation is complete.\n */\n async shutdown(id) {\n await (0, restapi_1.shutdownKernel)(id, this.serverSettings);\n await this.refreshRunning();\n }\n /**\n * Shut down all kernels.\n *\n * @returns A promise that resolves when all of the kernels are shut down.\n */\n async shutdownAll() {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n // Shut down all models.\n await Promise.all([...this._models.keys()].map(id => (0, restapi_1.shutdownKernel)(id, this.serverSettings)));\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n /**\n * Find a kernel by id.\n *\n * @param id - The id of the target kernel.\n *\n * @returns A promise that resolves with the kernel's model.\n */\n async findById(id) {\n if (this._models.has(id)) {\n return this._models.get(id);\n }\n await this.refreshRunning();\n return this._models.get(id);\n }\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n async requestRunning() {\n var _a, _b;\n let models;\n try {\n models = await (0, restapi_1.listRunning)(this.serverSettings);\n }\n catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof __1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n if (this.isDisposed) {\n return;\n }\n if (this._models.size === models.length &&\n models.every(model => {\n const existing = this._models.get(model.id);\n if (!existing) {\n return false;\n }\n return (existing.connections === model.connections &&\n existing.execution_state === model.execution_state &&\n existing.last_activity === model.last_activity &&\n existing.name === model.name &&\n existing.reason === model.reason &&\n existing.traceback === model.traceback);\n })) {\n // Identical models list (presuming models does not contain duplicate\n // ids), so just return\n return;\n }\n this._models = new Map(models.map(x => [x.id, x]));\n // For any kernel connection to a kernel that doesn't exist, notify it of\n // the shutdown.\n this._kernelConnections.forEach(kc => {\n if (!this._models.has(kc.id)) {\n kc.handleShutdown();\n }\n });\n this._runningChanged.emit(models);\n }\n /**\n * Handle a kernel starting.\n */\n _onStarted(kernelConnection) {\n this._kernelConnections.add(kernelConnection);\n kernelConnection.statusChanged.connect(this._onStatusChanged, this);\n kernelConnection.disposed.connect(this._onDisposed, this);\n }\n _onDisposed(kernelConnection) {\n this._kernelConnections.delete(kernelConnection);\n // A dispose emission could mean the server session is deleted, or that\n // the kernel JS object is disposed and the kernel still exists on the\n // server, so we refresh from the server to make sure we reflect the\n // server state.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n _onStatusChanged(kernelConnection, status) {\n if (status === 'dead') {\n // We asynchronously update our list of kernels, which asynchronously\n // will dispose them. We do not want to immediately dispose them because\n // there may be other signal handlers that want to be called.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n }\n}\nexports.KernelManager = KernelManager;\n/**\n * The namespace for `KernelManager` class statics.\n */\n(function (KernelManager) {\n /**\n * A no-op kernel manager to be used when starting kernels.\n */\n class NoopManager extends KernelManager {\n constructor() {\n super(...arguments);\n this._readyPromise = new Promise(() => {\n /* no-op */\n });\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return false;\n }\n /**\n * Used for testing.\n */\n get parentReady() {\n return super.ready;\n }\n /**\n * Start a new kernel - throws an error since it is not supported.\n */\n async startNew(createOptions = {}, connectOptions = {}) {\n return Promise.reject(new Error('Not implemented in no-op Kernel Manager'));\n }\n /**\n * Connect to an existing kernel - throws an error since it is not supported.\n */\n connectTo(options) {\n throw new Error('Not implemented in no-op Kernel Manager');\n }\n /**\n * Shut down a kernel by id - throws an error since it is not supported.\n */\n async shutdown(id) {\n return Promise.reject(new Error('Not implemented in no-op Kernel Manager'));\n }\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready() {\n return this.parentReady.then(() => this._readyPromise);\n }\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n async requestRunning() {\n return Promise.resolve();\n }\n }\n KernelManager.NoopManager = NoopManager;\n})(KernelManager = exports.KernelManager || (exports.KernelManager = {}));\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.supportedKernelWebSocketProtocols = exports.isInputReplyMsg = exports.isInputRequestMsg = exports.isDebugReplyMsg = exports.isDebugRequestMsg = exports.isExecuteReplyMsg = exports.isInfoRequestMsg = exports.isCommMsgMsg = exports.isCommCloseMsg = exports.isCommOpenMsg = exports.isDebugEventMsg = exports.isClearOutputMsg = exports.isStatusMsg = exports.isErrorMsg = exports.isExecuteResultMsg = exports.isExecuteInputMsg = exports.isUpdateDisplayDataMsg = exports.isDisplayDataMsg = exports.isStreamMsg = exports.createMessage = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nfunction createMessage(options) {\n var _a, _b, _c, _d, _e;\n return {\n buffers: (_a = options.buffers) !== null && _a !== void 0 ? _a : [],\n channel: options.channel,\n content: options.content,\n header: {\n date: new Date().toISOString(),\n msg_id: (_b = options.msgId) !== null && _b !== void 0 ? _b : coreutils_1.UUID.uuid4(),\n msg_type: options.msgType,\n session: options.session,\n username: (_c = options.username) !== null && _c !== void 0 ? _c : '',\n version: '5.2'\n },\n metadata: (_d = options.metadata) !== null && _d !== void 0 ? _d : {},\n parent_header: (_e = options.parentHeader) !== null && _e !== void 0 ? _e : {}\n };\n}\nexports.createMessage = createMessage;\n/**\n * Test whether a kernel message is a `'stream'` message.\n */\nfunction isStreamMsg(msg) {\n return msg.header.msg_type === 'stream';\n}\nexports.isStreamMsg = isStreamMsg;\n/**\n * Test whether a kernel message is an `'display_data'` message.\n */\nfunction isDisplayDataMsg(msg) {\n return msg.header.msg_type === 'display_data';\n}\nexports.isDisplayDataMsg = isDisplayDataMsg;\n/**\n * Test whether a kernel message is an `'update_display_data'` message.\n */\nfunction isUpdateDisplayDataMsg(msg) {\n return msg.header.msg_type === 'update_display_data';\n}\nexports.isUpdateDisplayDataMsg = isUpdateDisplayDataMsg;\n/**\n * Test whether a kernel message is an `'execute_input'` message.\n */\nfunction isExecuteInputMsg(msg) {\n return msg.header.msg_type === 'execute_input';\n}\nexports.isExecuteInputMsg = isExecuteInputMsg;\n/**\n * Test whether a kernel message is an `'execute_result'` message.\n */\nfunction isExecuteResultMsg(msg) {\n return msg.header.msg_type === 'execute_result';\n}\nexports.isExecuteResultMsg = isExecuteResultMsg;\n/**\n * Test whether a kernel message is an `'error'` message.\n */\nfunction isErrorMsg(msg) {\n return msg.header.msg_type === 'error';\n}\nexports.isErrorMsg = isErrorMsg;\n/**\n * Test whether a kernel message is a `'status'` message.\n */\nfunction isStatusMsg(msg) {\n return msg.header.msg_type === 'status';\n}\nexports.isStatusMsg = isStatusMsg;\n/**\n * Test whether a kernel message is a `'clear_output'` message.\n */\nfunction isClearOutputMsg(msg) {\n return msg.header.msg_type === 'clear_output';\n}\nexports.isClearOutputMsg = isClearOutputMsg;\n/**\n * Test whether a kernel message is an experimental `'debug_event'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nfunction isDebugEventMsg(msg) {\n return msg.header.msg_type === 'debug_event';\n}\nexports.isDebugEventMsg = isDebugEventMsg;\n/**\n * Test whether a kernel message is a `'comm_open'` message.\n */\nfunction isCommOpenMsg(msg) {\n return msg.header.msg_type === 'comm_open';\n}\nexports.isCommOpenMsg = isCommOpenMsg;\n/**\n * Test whether a kernel message is a `'comm_close'` message.\n */\nfunction isCommCloseMsg(msg) {\n return msg.header.msg_type === 'comm_close';\n}\nexports.isCommCloseMsg = isCommCloseMsg;\n/**\n * Test whether a kernel message is a `'comm_msg'` message.\n */\nfunction isCommMsgMsg(msg) {\n return msg.header.msg_type === 'comm_msg';\n}\nexports.isCommMsgMsg = isCommMsgMsg;\n/**\n * Test whether a kernel message is a `'kernel_info_request'` message.\n */\nfunction isInfoRequestMsg(msg) {\n return msg.header.msg_type === 'kernel_info_request';\n}\nexports.isInfoRequestMsg = isInfoRequestMsg;\n/**\n * Test whether a kernel message is an `'execute_reply'` message.\n */\nfunction isExecuteReplyMsg(msg) {\n return msg.header.msg_type === 'execute_reply';\n}\nexports.isExecuteReplyMsg = isExecuteReplyMsg;\n/**\n * Test whether a kernel message is an experimental `'debug_request'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nfunction isDebugRequestMsg(msg) {\n return msg.header.msg_type === 'debug_request';\n}\nexports.isDebugRequestMsg = isDebugRequestMsg;\n/**\n * Test whether a kernel message is an experimental `'debug_reply'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nfunction isDebugReplyMsg(msg) {\n return msg.header.msg_type === 'debug_reply';\n}\nexports.isDebugReplyMsg = isDebugReplyMsg;\n/**\n * Test whether a kernel message is an `'input_request'` message.\n */\nfunction isInputRequestMsg(msg) {\n return msg.header.msg_type === 'input_request';\n}\nexports.isInputRequestMsg = isInputRequestMsg;\n/**\n * Test whether a kernel message is an `'input_reply'` message.\n */\nfunction isInputReplyMsg(msg) {\n return msg.header.msg_type === 'input_reply';\n}\nexports.isInputReplyMsg = isInputReplyMsg;\n// ///////////////////////////////////////////////\n// Message (de)serialization\n// ///////////////////////////////////////////////\n/**\n * The list of supported kernel wire protocols over websocket.\n */\nvar supportedKernelWebSocketProtocols;\n(function (supportedKernelWebSocketProtocols) {\n supportedKernelWebSocketProtocols[\"v1KernelWebsocketJupyterOrg\"] = \"v1.kernel.websocket.jupyter.org\";\n})(supportedKernelWebSocketProtocols = exports.supportedKernelWebSocketProtocols || (exports.supportedKernelWebSocketProtocols = {}));\n//# sourceMappingURL=messages.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getKernelModel = exports.shutdownKernel = exports.interruptKernel = exports.restartKernel = exports.startNew = exports.listRunning = exports.KERNEL_SERVICE_URL = void 0;\nconst serverconnection_1 = require(\"../serverconnection\");\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst validate_1 = require(\"./validate\");\n/**\n * The url for the kernel service.\n */\nexports.KERNEL_SERVICE_URL = 'api/kernels';\n/**\n * Fetch the running kernels.\n *\n * @param settings - The optional server settings.\n *\n * @returns A promise that resolves with the list of running kernels.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModels)(data);\n return data;\n}\nexports.listRunning = listRunning;\n/**\n * Start a new kernel.\n *\n * @param options - The options used to create the kernel.\n *\n * @returns A promise that resolves with a kernel connection object.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function startNew(options = {}, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify(options)\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.startNew = startNew;\n/**\n * Restart a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response (and thus after a restart) and rejected otherwise.\n */\nasync function restartKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id), 'restart');\n const init = { method: 'POST' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModel)(data);\n}\nexports.restartKernel = restartKernel;\n/**\n * Interrupt a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function interruptKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id), 'interrupt');\n const init = { method: 'POST' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.interruptKernel = interruptKernel;\n/**\n * Shut down a kernel.\n *\n * @param id - The id of the running kernel.\n *\n * @param settings - The server settings for the request.\n *\n * @returns A promise that resolves when the kernel is shut down.\n *\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function shutdownKernel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id));\n const init = { method: 'DELETE' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const msg = `The kernel \"${id}\" does not exist on the server`;\n console.warn(msg);\n }\n else if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.shutdownKernel = shutdownKernel;\n/**\n * Get a full kernel model from the server by kernel id string.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nasync function getKernelModel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.KERNEL_SERVICE_URL, encodeURIComponent(id));\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status === 404) {\n return undefined;\n }\n else if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.getKernelModel = getKernelModel;\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deserialize = exports.serialize = void 0;\nconst KernelMessage = __importStar(require(\"./messages\"));\n/**\n * Serialize a kernel message for transport.\n */\nfunction serialize(msg, protocol = '') {\n switch (protocol) {\n case KernelMessage.supportedKernelWebSocketProtocols\n .v1KernelWebsocketJupyterOrg:\n return Private.serializeV1KernelWebsocketJupyterOrg(msg);\n default:\n return Private.serializeDefault(msg);\n }\n}\nexports.serialize = serialize;\n/**\n * Deserialize and return the unpacked message.\n */\nfunction deserialize(data, protocol = '') {\n switch (protocol) {\n case KernelMessage.supportedKernelWebSocketProtocols\n .v1KernelWebsocketJupyterOrg:\n return Private.deserializeV1KernelWebsocketJupyterOrg(data);\n default:\n return Private.deserializeDefault(data);\n }\n}\nexports.deserialize = deserialize;\nvar Private;\n(function (Private) {\n /**\n * Deserialize and return the unpacked message.\n * Protocol `v1.kernel.websocket.jupyter.org`\n */\n function deserializeV1KernelWebsocketJupyterOrg(binMsg) {\n let msg;\n const data = new DataView(binMsg);\n const offsetNumber = Number(data.getBigUint64(0, true /* littleEndian */));\n let offsets = [];\n for (let i = 0; i < offsetNumber; i++) {\n // WARNING: we cast our 64-bit unsigned int to a number!\n // so offsets cannot index up to 2**64 bytes\n offsets.push(Number(data.getBigUint64(8 * (i + 1), true /* littleEndian */)));\n }\n const decoder = new TextDecoder('utf8');\n const channel = decoder.decode(binMsg.slice(offsets[0], offsets[1]));\n const header = JSON.parse(decoder.decode(binMsg.slice(offsets[1], offsets[2])));\n const parent_header = JSON.parse(decoder.decode(binMsg.slice(offsets[2], offsets[3])));\n const metadata = JSON.parse(decoder.decode(binMsg.slice(offsets[3], offsets[4])));\n const content = JSON.parse(decoder.decode(binMsg.slice(offsets[4], offsets[5])));\n let buffers = [];\n for (let i = 5; i < offsets.length - 1; i++) {\n buffers.push(new DataView(binMsg.slice(offsets[i], offsets[i + 1])));\n }\n msg = {\n channel,\n header,\n parent_header,\n metadata,\n content,\n buffers\n };\n return msg;\n }\n Private.deserializeV1KernelWebsocketJupyterOrg = deserializeV1KernelWebsocketJupyterOrg;\n /**\n * Serialize a kernel message for transport.\n * Protocol `v1.kernel.websocket.jupyter.org`\n */\n function serializeV1KernelWebsocketJupyterOrg(msg) {\n const header = JSON.stringify(msg.header);\n const parentHeader = msg.parent_header == null ? '{}' : JSON.stringify(msg.parent_header);\n const metadata = JSON.stringify(msg.metadata);\n const content = JSON.stringify(msg.content);\n const buffers = msg.buffers !== undefined ? msg.buffers : [];\n const offsetNumber = 1 + 4 + buffers.length + 1;\n let offsets = [];\n offsets.push(8 * (1 + offsetNumber));\n offsets.push(msg.channel.length + offsets[offsets.length - 1]);\n const encoder = new TextEncoder();\n const channelEncoded = encoder.encode(msg.channel);\n const headerEncoded = encoder.encode(header);\n const parentHeaderEncoded = encoder.encode(parentHeader);\n const metadataEncoded = encoder.encode(metadata);\n const contentEncoded = encoder.encode(content);\n const binMsgNoBuff = new Uint8Array(channelEncoded.length +\n headerEncoded.length +\n parentHeaderEncoded.length +\n metadataEncoded.length +\n contentEncoded.length);\n binMsgNoBuff.set(channelEncoded);\n binMsgNoBuff.set(headerEncoded, channelEncoded.length);\n binMsgNoBuff.set(parentHeaderEncoded, channelEncoded.length + headerEncoded.length);\n binMsgNoBuff.set(metadataEncoded, channelEncoded.length + headerEncoded.length + parentHeaderEncoded.length);\n binMsgNoBuff.set(contentEncoded, channelEncoded.length +\n headerEncoded.length +\n parentHeaderEncoded.length +\n metadataEncoded.length);\n for (let length of [\n headerEncoded.length,\n parentHeaderEncoded.length,\n metadataEncoded.length,\n contentEncoded.length\n ]) {\n offsets.push(length + offsets[offsets.length - 1]);\n }\n let buffersByteLength = 0;\n for (let buffer of buffers) {\n let length = buffer.byteLength;\n offsets.push(length + offsets[offsets.length - 1]);\n buffersByteLength += length;\n }\n const binMsg = new Uint8Array(8 * (1 + offsetNumber) + binMsgNoBuff.byteLength + buffersByteLength);\n const word = new ArrayBuffer(8);\n const data = new DataView(word);\n data.setBigUint64(0, BigInt(offsetNumber), true /* littleEndian */);\n binMsg.set(new Uint8Array(word), 0);\n for (let i = 0; i < offsets.length; i++) {\n data.setBigUint64(0, BigInt(offsets[i]), true /* littleEndian */);\n binMsg.set(new Uint8Array(word), 8 * (i + 1));\n }\n binMsg.set(binMsgNoBuff, offsets[0]);\n for (let i = 0; i < buffers.length; i++) {\n const buffer = buffers[i];\n binMsg.set(new Uint8Array(ArrayBuffer.isView(buffer) ? buffer.buffer : buffer), offsets[5 + i]);\n }\n return binMsg.buffer;\n }\n Private.serializeV1KernelWebsocketJupyterOrg = serializeV1KernelWebsocketJupyterOrg;\n /**\n * Deserialize and return the unpacked message.\n * Default protocol\n *\n * #### Notes\n * Handles JSON blob strings and binary messages.\n */\n function deserializeDefault(data) {\n let value;\n if (typeof data === 'string') {\n value = JSON.parse(data);\n }\n else {\n value = deserializeBinary(data);\n }\n return value;\n }\n Private.deserializeDefault = deserializeDefault;\n /**\n * Serialize a kernel message for transport.\n * Default protocol\n *\n * #### Notes\n * If there is binary content, an `ArrayBuffer` is returned,\n * otherwise the message is converted to a JSON string.\n */\n function serializeDefault(msg) {\n var _a;\n let value;\n if ((_a = msg.buffers) === null || _a === void 0 ? void 0 : _a.length) {\n value = serializeBinary(msg);\n }\n else {\n value = JSON.stringify(msg);\n }\n return value;\n }\n Private.serializeDefault = serializeDefault;\n /**\n * Deserialize a binary message to a Kernel Message.\n */\n function deserializeBinary(buf) {\n const data = new DataView(buf);\n // read the header: 1 + nbufs 32b integers\n const nbufs = data.getUint32(0);\n const offsets = [];\n if (nbufs < 2) {\n throw new Error('Invalid incoming Kernel Message');\n }\n for (let i = 1; i <= nbufs; i++) {\n offsets.push(data.getUint32(i * 4));\n }\n const jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1]));\n const msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes));\n // the remaining chunks are stored as DataViews in msg.buffers\n msg.buffers = [];\n for (let i = 1; i < nbufs; i++) {\n const start = offsets[i];\n const stop = offsets[i + 1] || buf.byteLength;\n msg.buffers.push(new DataView(buf.slice(start, stop)));\n }\n return msg;\n }\n /**\n * Implement the binary serialization protocol.\n *\n * Serialize Kernel message to ArrayBuffer.\n */\n function serializeBinary(msg) {\n const offsets = [];\n const buffers = [];\n const encoder = new TextEncoder();\n let origBuffers = [];\n if (msg.buffers !== undefined) {\n origBuffers = msg.buffers;\n delete msg['buffers'];\n }\n const jsonUtf8 = encoder.encode(JSON.stringify(msg));\n buffers.push(jsonUtf8.buffer);\n for (let i = 0; i < origBuffers.length; i++) {\n // msg.buffers elements could be either views or ArrayBuffers\n // buffers elements are ArrayBuffers\n const b = origBuffers[i];\n buffers.push(ArrayBuffer.isView(b) ? b.buffer : b);\n }\n const nbufs = buffers.length;\n offsets.push(4 * (nbufs + 1));\n for (let i = 0; i + 1 < buffers.length; i++) {\n offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength);\n }\n const msgBuf = new Uint8Array(offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength);\n // use DataView.setUint32 for network byte-order\n const view = new DataView(msgBuf.buffer);\n // write nbufs to first 4 bytes\n view.setUint32(0, nbufs);\n // write offsets to next 4 * nbufs bytes\n for (let i = 0; i < offsets.length; i++) {\n view.setUint32(4 * (i + 1), offsets[i]);\n }\n // write all the buffers at their respective offsets\n for (let i = 0; i < buffers.length; i++) {\n msgBuf.set(new Uint8Array(buffers[i]), offsets[i]);\n }\n return msgBuf.buffer;\n }\n})(Private || (Private = {}));\n//# sourceMappingURL=serialize.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateModels = exports.validateModel = exports.validateMessage = void 0;\nconst validate_1 = require(\"../validate\");\n/**\n * Required fields for `IKernelHeader`.\n */\nconst HEADER_FIELDS = ['username', 'version', 'session', 'msg_id', 'msg_type'];\n/**\n * Required fields and types for contents of various types of `kernel.IMessage`\n * messages on the iopub channel.\n */\nconst IOPUB_CONTENT_FIELDS = {\n stream: { name: 'string', text: 'string' },\n display_data: { data: 'object', metadata: 'object' },\n execute_input: { code: 'string', execution_count: 'number' },\n execute_result: {\n execution_count: 'number',\n data: 'object',\n metadata: 'object'\n },\n error: { ename: 'string', evalue: 'string', traceback: 'object' },\n status: {\n execution_state: [\n 'string',\n ['starting', 'idle', 'busy', 'restarting', 'dead']\n ]\n },\n clear_output: { wait: 'boolean' },\n comm_open: { comm_id: 'string', target_name: 'string', data: 'object' },\n comm_msg: { comm_id: 'string', data: 'object' },\n comm_close: { comm_id: 'string' },\n shutdown_reply: { restart: 'boolean' } // Emitted by the IPython kernel.\n};\n/**\n * Validate the header of a kernel message.\n */\nfunction validateHeader(header) {\n for (let i = 0; i < HEADER_FIELDS.length; i++) {\n (0, validate_1.validateProperty)(header, HEADER_FIELDS[i], 'string');\n }\n}\n/**\n * Validate a kernel message object.\n */\nfunction validateMessage(msg) {\n (0, validate_1.validateProperty)(msg, 'metadata', 'object');\n (0, validate_1.validateProperty)(msg, 'content', 'object');\n (0, validate_1.validateProperty)(msg, 'channel', 'string');\n validateHeader(msg.header);\n if (msg.channel === 'iopub') {\n validateIOPubContent(msg);\n }\n}\nexports.validateMessage = validateMessage;\n/**\n * Validate content an kernel message on the iopub channel.\n */\nfunction validateIOPubContent(msg) {\n if (msg.channel === 'iopub') {\n const fields = IOPUB_CONTENT_FIELDS[msg.header.msg_type];\n // Check for unknown message type.\n if (fields === undefined) {\n return;\n }\n const names = Object.keys(fields);\n const content = msg.content;\n for (let i = 0; i < names.length; i++) {\n let args = fields[names[i]];\n if (!Array.isArray(args)) {\n args = [args];\n }\n (0, validate_1.validateProperty)(content, names[i], ...args);\n }\n }\n}\n/**\n * Validate a `Kernel.IModel` object.\n */\nfunction validateModel(model) {\n (0, validate_1.validateProperty)(model, 'name', 'string');\n (0, validate_1.validateProperty)(model, 'id', 'string');\n}\nexports.validateModel = validateModel;\n/**\n * Validate an array of `IModel` objects.\n */\nfunction validateModels(models) {\n if (!Array.isArray(models)) {\n throw new Error('Invalid kernel list');\n }\n models.forEach(d => validateModel(d));\n}\nexports.validateModels = validateModels;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelSpecAPI = exports.KernelSpec = void 0;\nconst KernelSpec = __importStar(require(\"./kernelspec\"));\nexports.KernelSpec = KernelSpec;\nconst KernelSpecAPI = __importStar(require(\"./restapi\"));\nexports.KernelSpecAPI = KernelSpecAPI;\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=kernelspec.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KernelSpecManager = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst restapi = __importStar(require(\"./restapi\"));\nconst basemanager_1 = require(\"../basemanager\");\n/**\n * An implementation of a kernel spec manager.\n */\nclass KernelSpecManager extends basemanager_1.BaseManager {\n /**\n * Construct a new kernel spec manager.\n *\n * @param options - The default options for kernel.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n this._connectionFailure = new signaling_1.Signal(this);\n this._specs = null;\n this._specsChanged = new signaling_1.Signal(this);\n // Initialize internal data.\n this._ready = Promise.all([this.requestSpecs()])\n .then(_ => undefined)\n .catch(_ => undefined)\n .then(() => {\n if (this.isDisposed) {\n return;\n }\n this._isReady = true;\n });\n this._pollSpecs = new polling_1.Poll({\n auto: false,\n factory: () => this.requestSpecs(),\n frequency: {\n interval: 61 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:KernelSpecManager#specs`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n void this.ready.then(() => {\n void this._pollSpecs.start();\n });\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * Get the most recently fetched kernel specs.\n */\n get specs() {\n return this._specs;\n }\n /**\n * A signal emitted when the specs change.\n */\n get specsChanged() {\n return this._specsChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n this._pollSpecs.dispose();\n super.dispose();\n }\n /**\n * Force a refresh of the specs from the server.\n *\n * @returns A promise that resolves when the specs are fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshSpecs() {\n await this._pollSpecs.refresh();\n await this._pollSpecs.tick;\n }\n /**\n * Execute a request to the server to poll specs and update state.\n */\n async requestSpecs() {\n const specs = await restapi.getSpecs(this.serverSettings);\n if (this.isDisposed) {\n return;\n }\n if (!coreutils_1.JSONExt.deepEqual(specs, this._specs)) {\n this._specs = specs;\n this._specsChanged.emit(specs);\n }\n }\n}\nexports.KernelSpecManager = KernelSpecManager;\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getSpecs = void 0;\nconst serverconnection_1 = require(\"../serverconnection\");\nconst validate_1 = require(\"./validate\");\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\n/**\n * The url for the kernelspec service.\n */\nconst KERNELSPEC_SERVICE_URL = 'api/kernelspecs';\n/**\n * Fetch all of the kernel specs.\n *\n * @param settings - The optional server settings.\n * @param useCache - Whether to use the cache. If false, always request.\n *\n * @returns A promise that resolves with the kernel specs.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernelspecs).\n */\nasync function getSpecs(settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, KERNELSPEC_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n return (0, validate_1.validateSpecModels)(data);\n}\nexports.getSpecs = getSpecs;\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateSpecModels = exports.validateSpecModel = void 0;\nconst validate_1 = require(\"../validate\");\n/**\n * Validate a server kernelspec model to a client side model.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction validateSpecModel(data) {\n const spec = data.spec;\n if (!spec) {\n throw new Error('Invalid kernel spec');\n }\n (0, validate_1.validateProperty)(data, 'name', 'string');\n (0, validate_1.validateProperty)(data, 'resources', 'object');\n (0, validate_1.validateProperty)(spec, 'language', 'string');\n (0, validate_1.validateProperty)(spec, 'display_name', 'string');\n (0, validate_1.validateProperty)(spec, 'argv', 'array');\n let metadata = null;\n if (spec.hasOwnProperty('metadata')) {\n (0, validate_1.validateProperty)(spec, 'metadata', 'object');\n metadata = spec.metadata;\n }\n let env = null;\n if (spec.hasOwnProperty('env')) {\n (0, validate_1.validateProperty)(spec, 'env', 'object');\n env = spec.env;\n }\n return {\n name: data.name,\n resources: data.resources,\n language: spec.language,\n display_name: spec.display_name,\n argv: spec.argv,\n metadata,\n env\n };\n}\nexports.validateSpecModel = validateSpecModel;\n/**\n * Validate a `Kernel.ISpecModels` object.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction validateSpecModels(data) {\n if (!data.hasOwnProperty('kernelspecs')) {\n throw new Error('No kernelspecs found');\n }\n let keys = Object.keys(data.kernelspecs);\n const kernelspecs = Object.create(null);\n let defaultSpec = data.default;\n for (let i = 0; i < keys.length; i++) {\n const ks = data.kernelspecs[keys[i]];\n try {\n kernelspecs[keys[i]] = validateSpecModel(ks);\n }\n catch (err) {\n // Remove the errant kernel spec.\n console.warn(`Removing errant kernel spec: ${keys[i]}`);\n }\n }\n keys = Object.keys(kernelspecs);\n if (!keys.length) {\n throw new Error('No valid kernelspecs found');\n }\n if (!defaultSpec ||\n typeof defaultSpec !== 'string' ||\n !(defaultSpec in kernelspecs)) {\n defaultSpec = keys[0];\n console.warn(`Default kernel not found, using '${keys[0]}'`);\n }\n return {\n default: defaultSpec,\n kernelspecs\n };\n}\nexports.validateSpecModels = validateSpecModels;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ServiceManager = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\nconst builder_1 = require(\"./builder\");\nconst contents_1 = require(\"./contents\");\nconst event_1 = require(\"./event\");\nconst kernel_1 = require(\"./kernel\");\nconst kernelspec_1 = require(\"./kernelspec\");\nconst nbconvert_1 = require(\"./nbconvert\");\nconst serverconnection_1 = require(\"./serverconnection\");\nconst session_1 = require(\"./session\");\nconst setting_1 = require(\"./setting\");\nconst terminal_1 = require(\"./terminal\");\nconst user_1 = require(\"./user\");\nconst workspace_1 = require(\"./workspace\");\n/**\n * A Jupyter services manager.\n */\nclass ServiceManager {\n /**\n * Construct a new services provider.\n */\n constructor(options = {}) {\n var _a, _b;\n this._isDisposed = false;\n this._connectionFailure = new signaling_1.Signal(this);\n this._isReady = false;\n const defaultDrive = options.defaultDrive;\n const serverSettings = (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n const standby = (_b = options.standby) !== null && _b !== void 0 ? _b : 'when-hidden';\n const normalized = { defaultDrive, serverSettings, standby };\n this.serverSettings = serverSettings;\n this.contents = options.contents || new contents_1.ContentsManager(normalized);\n this.events = options.events || new event_1.EventManager(normalized);\n this.kernels = options.kernels || new kernel_1.KernelManager(normalized);\n this.sessions =\n options.sessions ||\n new session_1.SessionManager({\n ...normalized,\n kernelManager: this.kernels\n });\n this.settings = options.settings || new setting_1.SettingManager(normalized);\n this.terminals = options.terminals || new terminal_1.TerminalManager(normalized);\n this.builder = options.builder || new builder_1.BuildManager(normalized);\n this.workspaces = options.workspaces || new workspace_1.WorkspaceManager(normalized);\n this.nbconvert = options.nbconvert || new nbconvert_1.NbConvertManager(normalized);\n this.kernelspecs = options.kernelspecs || new kernelspec_1.KernelSpecManager(normalized);\n this.user = options.user || new user_1.UserManager(normalized);\n // Proxy all connection failures from the individual service managers.\n this.kernelspecs.connectionFailure.connect(this._onConnectionFailure, this);\n this.sessions.connectionFailure.connect(this._onConnectionFailure, this);\n this.terminals.connectionFailure.connect(this._onConnectionFailure, this);\n // Define promises that need to be resolved before service manager is ready.\n const readyList = [this.sessions.ready, this.kernelspecs.ready];\n if (this.terminals.isAvailable()) {\n readyList.push(this.terminals.ready);\n }\n this._readyPromise = Promise.all(readyList).then(() => {\n this._isReady = true;\n });\n }\n /**\n * A signal emitted when there is a connection failure with the kernel.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Test whether the service manager is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n this.contents.dispose();\n this.events.dispose();\n this.sessions.dispose();\n this.terminals.dispose();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._readyPromise;\n }\n _onConnectionFailure(sender, err) {\n this._connectionFailure.emit(err);\n }\n}\nexports.ServiceManager = ServiceManager;\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NbConvertManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst serverconnection_1 = require(\"../serverconnection\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\n/**\n * The url for the lab nbconvert service.\n */\nconst NBCONVERT_SETTINGS_URL = 'api/nbconvert';\n/**\n * The nbconvert API service manager.\n */\nclass NbConvertManager {\n /**\n * Create a new nbconvert manager.\n */\n constructor(options = {}) {\n var _a;\n this._exportFormats = null;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * Fetch and cache the export formats from the expensive nbconvert handler.\n */\n async fetchExportFormats() {\n this._requestingFormats = new coreutils_2.PromiseDelegate();\n this._exportFormats = null;\n const base = this.serverSettings.baseUrl;\n const url = coreutils_1.URLExt.join(base, NBCONVERT_SETTINGS_URL);\n const { serverSettings } = this;\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n const exportList = {};\n const keys = Object.keys(data);\n keys.forEach(function (key) {\n const mimeType = data[key].output_mimetype;\n exportList[key] = { output_mimetype: mimeType };\n });\n this._exportFormats = exportList;\n this._requestingFormats.resolve(exportList);\n return exportList;\n }\n /**\n * Get the list of export formats, preferring pre-cached ones.\n */\n async getExportFormats(force = true) {\n if (this._requestingFormats) {\n return this._requestingFormats.promise;\n }\n if (force || !this._exportFormats) {\n return await this.fetchExportFormats();\n }\n return this._exportFormats;\n }\n}\nexports.NbConvertManager = NbConvertManager;\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ServerConnection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nlet WEBSOCKET;\nif (typeof window === 'undefined') {\n // Mangle the require statements so it does not get picked up in the\n // browser assets.\n WEBSOCKET = require('ws');\n}\nelse {\n WEBSOCKET = WebSocket;\n}\n/**\n * The namespace for ServerConnection functions.\n *\n * #### Notes\n * This is only intended to manage communication with the Jupyter server.\n *\n * The default values can be used in a JupyterLab or Jupyter Notebook context.\n *\n * We use `token` authentication if available, falling back on an XSRF\n * cookie if one has been provided on the `document`.\n *\n * A content type of `'application/json'` is added when using authentication\n * and there is no body data to allow the server to prevent malicious forms.\n */\nvar ServerConnection;\n(function (ServerConnection) {\n /**\n * Create a settings object given a subset of options.\n *\n * @param options - An optional partial set of options.\n *\n * @returns The full settings object.\n */\n function makeSettings(options) {\n return Private.makeSettings(options);\n }\n ServerConnection.makeSettings = makeSettings;\n /**\n * Make an request to the notebook server.\n *\n * @param url - The url for the request.\n *\n * @param init - The initialization options for the request.\n *\n * @param settings - The server settings to apply to the request.\n *\n * @returns a Promise that resolves with the response.\n *\n * @throws If the url of the request is not a notebook server url.\n *\n * #### Notes\n * The `url` must start with `settings.baseUrl`. The `init` settings are\n * merged with `settings.init`, with `init` taking precedence.\n * The headers in the two objects are not merged.\n * If there is no body data, we set the content type to `application/json`\n * because it is required by the Notebook server.\n */\n function makeRequest(url, init, settings) {\n return Private.handleRequest(url, init, settings);\n }\n ServerConnection.makeRequest = makeRequest;\n /**\n * A wrapped error for a fetch response.\n */\n class ResponseError extends Error {\n /**\n * Create a ResponseError from a response, handling the traceback and message\n * as appropriate.\n *\n * @param response The response object.\n *\n * @returns A promise that resolves with a `ResponseError` object.\n */\n static async create(response) {\n try {\n const data = await response.json();\n const { message, traceback } = data;\n if (traceback) {\n console.error(traceback);\n }\n return new ResponseError(response, message !== null && message !== void 0 ? message : ResponseError._defaultMessage(response), traceback !== null && traceback !== void 0 ? traceback : '');\n }\n catch (e) {\n console.debug(e);\n return new ResponseError(response);\n }\n }\n /**\n * Create a new response error.\n */\n constructor(response, message = ResponseError._defaultMessage(response), traceback = '') {\n super(message);\n this.response = response;\n this.traceback = traceback;\n }\n static _defaultMessage(response) {\n return `Invalid response: ${response.status} ${response.statusText}`;\n }\n }\n ServerConnection.ResponseError = ResponseError;\n /**\n * A wrapped error for a network error.\n */\n class NetworkError extends TypeError {\n /**\n * Create a new network error.\n */\n constructor(original) {\n super(original.message);\n this.stack = original.stack;\n }\n }\n ServerConnection.NetworkError = NetworkError;\n})(ServerConnection = exports.ServerConnection || (exports.ServerConnection = {}));\n/**\n * The namespace for module private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Handle the server connection settings, returning a new value.\n */\n function makeSettings(options = {}) {\n var _a;\n const pageBaseUrl = coreutils_1.PageConfig.getBaseUrl();\n const pageWsUrl = coreutils_1.PageConfig.getWsUrl();\n const baseUrl = coreutils_1.URLExt.normalize(options.baseUrl) || pageBaseUrl;\n let wsUrl = options.wsUrl;\n // Prefer the default wsUrl if we are using the default baseUrl.\n if (!wsUrl && baseUrl === pageBaseUrl) {\n wsUrl = pageWsUrl;\n }\n // Otherwise convert the baseUrl to a wsUrl if possible.\n if (!wsUrl && baseUrl.indexOf('http') === 0) {\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n // Otherwise fall back on the default wsUrl.\n wsUrl = wsUrl !== null && wsUrl !== void 0 ? wsUrl : pageWsUrl;\n return {\n init: { cache: 'no-store', credentials: 'same-origin' },\n fetch,\n Headers,\n Request,\n WebSocket: WEBSOCKET,\n token: coreutils_1.PageConfig.getToken(),\n appUrl: coreutils_1.PageConfig.getOption('appUrl'),\n appendToken: typeof window === 'undefined' ||\n (typeof process !== 'undefined' &&\n ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a.JEST_WORKER_ID) !== undefined) ||\n coreutils_1.URLExt.getHostName(pageBaseUrl) !== coreutils_1.URLExt.getHostName(wsUrl),\n ...options,\n baseUrl,\n wsUrl\n };\n }\n Private.makeSettings = makeSettings;\n /**\n * Handle a request.\n *\n * @param url - The url for the request.\n *\n * @param init - The overrides for the request init.\n *\n * @param settings - The settings object for the request.\n *\n * #### Notes\n * The `url` must start with `settings.baseUrl`. The `init` settings\n * take precedence over `settings.init`.\n */\n function handleRequest(url, init, settings) {\n var _a;\n // Handle notebook server requests.\n if (url.indexOf(settings.baseUrl) !== 0) {\n throw new Error('Can only be used for notebook server requests');\n }\n // Use explicit cache buster when `no-store` is set since\n // not all browsers use it properly.\n const cache = (_a = init.cache) !== null && _a !== void 0 ? _a : settings.init.cache;\n if (cache === 'no-store') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache\n url += (/\\?/.test(url) ? '&' : '?') + new Date().getTime();\n }\n const request = new settings.Request(url, { ...settings.init, ...init });\n // Handle authentication. Authentication can be overdetermined by\n // settings token and XSRF token.\n let authenticated = false;\n if (settings.token) {\n authenticated = true;\n request.headers.append('Authorization', `token ${settings.token}`);\n }\n if (typeof document !== 'undefined' && (document === null || document === void 0 ? void 0 : document.cookie)) {\n const xsrfToken = getCookie('_xsrf');\n if (xsrfToken !== undefined) {\n authenticated = true;\n request.headers.append('X-XSRFToken', xsrfToken);\n }\n }\n // Set the content type if there is no given data and we are\n // using an authenticated connection.\n if (!request.headers.has('Content-Type') && authenticated) {\n request.headers.set('Content-Type', 'application/json');\n }\n // Use `call` to avoid a `TypeError` in the browser.\n return settings.fetch.call(null, request).catch((e) => {\n // Convert the TypeError into a more specific error.\n throw new ServerConnection.NetworkError(e);\n });\n // TODO: *this* is probably where we need a system-wide connectionFailure\n // signal we can hook into.\n }\n Private.handleRequest = handleRequest;\n /**\n * Get a cookie from the document.\n */\n function getCookie(name) {\n // From http://www.tornadoweb.org/en/stable/guide/security.html\n const matches = document.cookie.match('\\\\b' + name + '=([^;]*)\\\\b');\n return matches === null || matches === void 0 ? void 0 : matches[1];\n }\n})(Private || (Private = {}));\n//# sourceMappingURL=serverconnection.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SessionConnection = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst restapi_1 = require(\"./restapi\");\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * Session object for accessing the session REST api. The session\n * should be used to start kernels and then shut them down -- for\n * all other kernel operations, the kernel object should be used.\n */\nclass SessionConnection {\n /**\n * Construct a new session.\n */\n constructor(options) {\n var _a, _b, _c, _d;\n this._id = '';\n this._path = '';\n this._name = '';\n this._type = '';\n this._kernel = null;\n this._isDisposed = false;\n this._disposed = new signaling_1.Signal(this);\n this._kernelChanged = new signaling_1.Signal(this);\n this._statusChanged = new signaling_1.Signal(this);\n this._connectionStatusChanged = new signaling_1.Signal(this);\n this._pendingInput = new signaling_1.Signal(this);\n this._iopubMessage = new signaling_1.Signal(this);\n this._unhandledMessage = new signaling_1.Signal(this);\n this._anyMessage = new signaling_1.Signal(this);\n this._propertyChanged = new signaling_1.Signal(this);\n this._id = options.model.id;\n this._name = options.model.name;\n this._path = options.model.path;\n this._type = options.model.type;\n this._username = (_a = options.username) !== null && _a !== void 0 ? _a : '';\n this._clientId = (_b = options.clientId) !== null && _b !== void 0 ? _b : coreutils_1.UUID.uuid4();\n this._connectToKernel = options.connectToKernel;\n this._kernelConnectionOptions = (_c = options.kernelConnectionOptions) !== null && _c !== void 0 ? _c : {};\n this.serverSettings =\n (_d = options.serverSettings) !== null && _d !== void 0 ? _d : __1.ServerConnection.makeSettings();\n this.setupKernel(options.model.kernel);\n }\n /**\n * A signal emitted when the session is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * A signal emitted when the kernel changes.\n */\n get kernelChanged() {\n return this._kernelChanged;\n }\n /**\n * A signal proxied from the connection about the kernel status.\n */\n get statusChanged() {\n return this._statusChanged;\n }\n /**\n * A signal proxied from the kernel about the connection status.\n */\n get connectionStatusChanged() {\n return this._connectionStatusChanged;\n }\n /**\n * A signal proxied from the kernel pending input.\n */\n get pendingInput() {\n return this._pendingInput;\n }\n /**\n * A signal proxied from the kernel about iopub kernel messages.\n */\n get iopubMessage() {\n return this._iopubMessage;\n }\n /**\n * A signal proxied from the kernel for an unhandled kernel message.\n */\n get unhandledMessage() {\n return this._unhandledMessage;\n }\n /**\n * A signal proxied from the kernel emitted for any kernel message.\n *\n * #### Notes\n * The behavior is undefined if the message is modified during message\n * handling. As such, it should be treated as read-only.\n */\n get anyMessage() {\n return this._anyMessage;\n }\n /**\n * A signal emitted when a session property changes.\n */\n get propertyChanged() {\n return this._propertyChanged;\n }\n /**\n * Get the session id.\n */\n get id() {\n return this._id;\n }\n /**\n * Get the session kernel connection object.\n *\n * #### Notes\n * This is a read-only property, and can be altered by [changeKernel].\n */\n get kernel() {\n return this._kernel;\n }\n /**\n * Get the session path.\n */\n get path() {\n return this._path;\n }\n /**\n * Get the session type.\n */\n get type() {\n return this._type;\n }\n /**\n * Get the session name.\n */\n get name() {\n return this._name;\n }\n /**\n * Get the model associated with the session.\n */\n get model() {\n return {\n id: this.id,\n kernel: this.kernel && { id: this.kernel.id, name: this.kernel.name },\n path: this._path,\n type: this._type,\n name: this._name\n };\n }\n /**\n * Test whether the session has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Update the session based on a session model from the server.\n *\n * #### Notes\n * This only updates this session connection instance. Use `setPath`,\n * `setName`, `setType`, and `changeKernel` to change the session values on\n * the server.\n */\n update(model) {\n const oldModel = this.model;\n this._path = model.path;\n this._name = model.name;\n this._type = model.type;\n if ((this._kernel === null && model.kernel !== null) ||\n (this._kernel !== null && model.kernel === null) ||\n (this._kernel !== null &&\n model.kernel !== null &&\n this._kernel.id !== model.kernel.id)) {\n if (this._kernel !== null) {\n this._kernel.dispose();\n }\n const oldValue = this._kernel || null;\n this.setupKernel(model.kernel);\n const newValue = this._kernel || null;\n this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });\n }\n this._handleModelChange(oldModel);\n }\n /**\n * Dispose of the resources held by the session.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n if (this._kernel) {\n this._kernel.dispose();\n const oldValue = this._kernel;\n this._kernel = null;\n const newValue = this._kernel;\n this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });\n }\n signaling_1.Signal.clearData(this);\n }\n /**\n * Change the session path.\n *\n * @param path - The new session path.\n *\n * @returns A promise that resolves when the session has renamed.\n *\n * #### Notes\n * This uses the Jupyter REST API, and the response is validated.\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async setPath(path) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ path });\n }\n /**\n * Change the session name.\n */\n async setName(name) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ name });\n }\n /**\n * Change the session type.\n */\n async setType(type) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ type });\n }\n /**\n * Change the kernel.\n *\n * @param options - The name or id of the new kernel.\n *\n * #### Notes\n * This shuts down the existing kernel and creates a new kernel,\n * keeping the existing session ID and session path.\n */\n async changeKernel(options) {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ kernel: options });\n return this.kernel;\n }\n /**\n * Kill the kernel and shutdown the session.\n *\n * @returns - The promise fulfilled on a valid response from the server.\n *\n * #### Notes\n * Uses the [Jupyter Notebook API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions), and validates the response.\n * Disposes of the session and emits a [sessionDied] signal on success.\n */\n async shutdown() {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await (0, restapi_1.shutdownSession)(this.id, this.serverSettings);\n this.dispose();\n }\n /**\n * Create a new kernel connection and connect to its signals.\n *\n * #### Notes\n * This method is not meant to be subclassed.\n */\n setupKernel(model) {\n if (model === null) {\n this._kernel = null;\n return;\n }\n const kc = this._connectToKernel({\n ...this._kernelConnectionOptions,\n model,\n username: this._username,\n clientId: this._clientId,\n serverSettings: this.serverSettings\n });\n this._kernel = kc;\n kc.statusChanged.connect(this.onKernelStatus, this);\n kc.connectionStatusChanged.connect(this.onKernelConnectionStatus, this);\n kc.pendingInput.connect(this.onPendingInput, this);\n kc.unhandledMessage.connect(this.onUnhandledMessage, this);\n kc.iopubMessage.connect(this.onIOPubMessage, this);\n kc.anyMessage.connect(this.onAnyMessage, this);\n }\n /**\n * Handle to changes in the Kernel status.\n */\n onKernelStatus(sender, state) {\n this._statusChanged.emit(state);\n }\n /**\n * Handle to changes in the Kernel status.\n */\n onKernelConnectionStatus(sender, state) {\n this._connectionStatusChanged.emit(state);\n }\n /**\n * Handle a change in the pendingInput.\n */\n onPendingInput(sender, state) {\n this._pendingInput.emit(state);\n }\n /**\n * Handle iopub kernel messages.\n */\n onIOPubMessage(sender, msg) {\n this._iopubMessage.emit(msg);\n }\n /**\n * Handle unhandled kernel messages.\n */\n onUnhandledMessage(sender, msg) {\n this._unhandledMessage.emit(msg);\n }\n /**\n * Handle any kernel messages.\n */\n onAnyMessage(sender, args) {\n this._anyMessage.emit(args);\n }\n /**\n * Send a PATCH to the server, updating the session path or the kernel.\n */\n async _patch(body) {\n const model = await (0, restapi_1.updateSession)({ ...body, id: this._id }, this.serverSettings);\n this.update(model);\n return model;\n }\n /**\n * Handle a change to the model.\n */\n _handleModelChange(oldModel) {\n if (oldModel.name !== this._name) {\n this._propertyChanged.emit('name');\n }\n if (oldModel.type !== this._type) {\n this._propertyChanged.emit('type');\n }\n if (oldModel.path !== this._path) {\n this._propertyChanged.emit('path');\n }\n }\n}\nexports.SessionConnection = SessionConnection;\n//# sourceMappingURL=default.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SessionAPI = exports.Session = void 0;\nconst Session = __importStar(require(\"./session\"));\nexports.Session = Session;\nconst SessionAPI = __importStar(require(\"./restapi\"));\nexports.SessionAPI = SessionAPI;\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SessionManager = void 0;\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"../serverconnection\");\nconst basemanager_1 = require(\"../basemanager\");\nconst default_1 = require(\"./default\");\nconst restapi_1 = require(\"./restapi\");\n/**\n * An implementation of a session manager.\n */\nclass SessionManager extends basemanager_1.BaseManager {\n /**\n * Construct a new session manager.\n *\n * @param options - The default options for each session.\n */\n constructor(options) {\n var _a;\n super(options);\n this._isReady = false;\n this._sessionConnections = new Set();\n this._models = new Map();\n this._runningChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // We define these here so they bind `this` correctly\n this._connectToKernel = (options) => {\n return this._kernelManager.connectTo(options);\n };\n this._kernelManager = options.kernelManager;\n // Start model polling with exponential backoff.\n this._pollModels = new polling_1.Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:SessionManager#models`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n if (this._kernelManager.isActive) {\n await this._kernelManager.ready;\n }\n this._isReady = true;\n })();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * A signal emitted when the running sessions change.\n */\n get runningChanged() {\n return this._runningChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._models.clear();\n this._sessionConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n /*\n * Connect to a running session. See also [[connectToSession]].\n */\n connectTo(options) {\n const sessionConnection = new default_1.SessionConnection({\n ...options,\n connectToKernel: this._connectToKernel,\n serverSettings: this.serverSettings\n });\n this._onStarted(sessionConnection);\n if (!this._models.has(options.model.id)) {\n // We trust the user to connect to an existing session, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return sessionConnection;\n }\n /**\n * Create an iterator over the most recent running sessions.\n *\n * @returns A new iterator over the running sessions.\n */\n running() {\n return this._models.values();\n }\n /**\n * Force a refresh of the running sessions.\n *\n * @returns A promise that with the list of running sessions.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n async refreshRunning() {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n /**\n * Start a new session. See also [[startNewSession]].\n *\n * @param createOptions - Options for creating the session\n *\n * @param connectOptions - Options for connecting to the session\n */\n async startNew(createOptions, connectOptions = {}) {\n const model = await (0, restapi_1.startSession)(createOptions, this.serverSettings);\n await this.refreshRunning();\n return this.connectTo({ ...connectOptions, model });\n }\n /**\n * Shut down a session by id.\n */\n async shutdown(id) {\n await (0, restapi_1.shutdownSession)(id, this.serverSettings);\n await this.refreshRunning();\n }\n /**\n * Shut down all sessions.\n *\n * @returns A promise that resolves when all of the kernels are shut down.\n */\n async shutdownAll() {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n // Shut down all models.\n await Promise.all([...this._models.keys()].map(id => (0, restapi_1.shutdownSession)(id, this.serverSettings)));\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n /**\n * Find a session associated with a path and stop it if it is the only session\n * using that kernel.\n *\n * @param path - The path in question.\n *\n * @returns A promise that resolves when the relevant sessions are stopped.\n */\n async stopIfNeeded(path) {\n try {\n const sessions = await (0, restapi_1.listRunning)(this.serverSettings);\n const matches = sessions.filter(value => value.path === path);\n if (matches.length === 1) {\n const id = matches[0].id;\n await this.shutdown(id);\n }\n }\n catch (error) {\n /* Always succeed. */\n }\n }\n /**\n * Find a session by id.\n */\n async findById(id) {\n if (this._models.has(id)) {\n return this._models.get(id);\n }\n await this.refreshRunning();\n return this._models.get(id);\n }\n /**\n * Find a session by path.\n */\n async findByPath(path) {\n for (const m of this._models.values()) {\n if (m.path === path) {\n return m;\n }\n }\n await this.refreshRunning();\n for (const m of this._models.values()) {\n if (m.path === path) {\n return m;\n }\n }\n return undefined;\n }\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n async requestRunning() {\n var _a, _b;\n let models;\n try {\n models = await (0, restapi_1.listRunning)(this.serverSettings);\n }\n catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof serverconnection_1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n if (this.isDisposed) {\n return;\n }\n if (this._models.size === models.length &&\n models.every(model => {\n var _a, _b, _c, _d;\n const existing = this._models.get(model.id);\n if (!existing) {\n return false;\n }\n return (((_a = existing.kernel) === null || _a === void 0 ? void 0 : _a.id) === ((_b = model.kernel) === null || _b === void 0 ? void 0 : _b.id) &&\n ((_c = existing.kernel) === null || _c === void 0 ? void 0 : _c.name) === ((_d = model.kernel) === null || _d === void 0 ? void 0 : _d.name) &&\n existing.name === model.name &&\n existing.path === model.path &&\n existing.type === model.type);\n })) {\n // Identical models list (presuming models does not contain duplicate\n // ids), so just return\n return;\n }\n this._models = new Map(models.map(x => [x.id, x]));\n this._sessionConnections.forEach(sc => {\n if (this._models.has(sc.id)) {\n sc.update(this._models.get(sc.id));\n }\n else {\n sc.dispose();\n }\n });\n this._runningChanged.emit(models);\n }\n /**\n * Handle a session starting.\n */\n _onStarted(sessionConnection) {\n this._sessionConnections.add(sessionConnection);\n sessionConnection.disposed.connect(this._onDisposed, this);\n sessionConnection.propertyChanged.connect(this._onChanged, this);\n sessionConnection.kernelChanged.connect(this._onChanged, this);\n }\n _onDisposed(sessionConnection) {\n this._sessionConnections.delete(sessionConnection);\n // A session termination emission could mean the server session is deleted,\n // or that the session JS object is disposed and the session still exists on\n // the server, so we refresh from the server to make sure we reflect the\n // server state.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n _onChanged() {\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n}\nexports.SessionManager = SessionManager;\n/**\n * The namespace for `SessionManager` class statics.\n */\n(function (SessionManager) {\n /**\n * A no-op session manager to be used when starting sessions is not supported.\n */\n class NoopManager extends SessionManager {\n constructor() {\n super(...arguments);\n this._readyPromise = new Promise(() => {\n /* no-op */\n });\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return false;\n }\n /**\n * Used for testing.\n */\n get parentReady() {\n return super.ready;\n }\n /**\n * Start a new session - throw an error since it is not supported.\n */\n async startNew(createOptions, connectOptions = {}) {\n return Promise.reject(new Error('Not implemented in no-op Session Manager'));\n }\n /*\n * Connect to a running session - throw an error since it is not supported.\n */\n connectTo(options) {\n throw Error('Not implemented in no-op Session Manager');\n }\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready() {\n return this.parentReady.then(() => this._readyPromise);\n }\n /**\n * Shut down a session by id - throw an error since it is not supported.\n */\n async shutdown(id) {\n return Promise.reject(new Error('Not implemented in no-op Session Manager'));\n }\n /**\n * Execute a request to the server to poll running sessions and update state.\n */\n async requestRunning() {\n return Promise.resolve();\n }\n }\n SessionManager.NoopManager = NoopManager;\n})(SessionManager = exports.SessionManager || (exports.SessionManager = {}));\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.updateSession = exports.startSession = exports.getSessionModel = exports.shutdownSession = exports.getSessionUrl = exports.listRunning = exports.SESSION_SERVICE_URL = void 0;\nconst serverconnection_1 = require(\"../serverconnection\");\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst validate_1 = require(\"./validate\");\n/**\n * The url for the session service.\n */\nexports.SESSION_SERVICE_URL = 'api/sessions';\n/**\n * List the running sessions.\n */\nasync function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.SESSION_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid Session list');\n }\n data.forEach(m => {\n (0, validate_1.updateLegacySessionModel)(m);\n (0, validate_1.validateModel)(m);\n });\n return data;\n}\nexports.listRunning = listRunning;\n/**\n * Get a session url.\n */\nfunction getSessionUrl(baseUrl, id) {\n return coreutils_1.URLExt.join(baseUrl, exports.SESSION_SERVICE_URL, id);\n}\nexports.getSessionUrl = getSessionUrl;\n/**\n * Shut down a session by id.\n */\nasync function shutdownSession(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n var _a;\n const url = getSessionUrl(settings.baseUrl, id);\n const init = { method: 'DELETE' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const data = await response.json();\n const msg = (_a = data.message) !== null && _a !== void 0 ? _a : `The session \"${id}\"\" does not exist on the server`;\n console.warn(msg);\n }\n else if (response.status === 410) {\n throw new serverconnection_1.ServerConnection.ResponseError(response, 'The kernel was deleted but the session was not');\n }\n else if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.shutdownSession = shutdownSession;\n/**\n * Get a full session model from the server by session id string.\n */\nasync function getSessionModel(id, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = getSessionUrl(settings.baseUrl, id);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.updateLegacySessionModel)(data);\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.getSessionModel = getSessionModel;\n/**\n * Create a new session, or return an existing session if the session path\n * already exists.\n */\nasync function startSession(options, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.SESSION_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify(options)\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.updateLegacySessionModel)(data);\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.startSession = startSession;\n/**\n * Send a PATCH to the server, updating the session path or the kernel.\n */\nasync function updateSession(model, settings = serverconnection_1.ServerConnection.makeSettings()) {\n const url = getSessionUrl(settings.baseUrl, model.id);\n const init = {\n method: 'PATCH',\n body: JSON.stringify(model)\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n (0, validate_1.updateLegacySessionModel)(data);\n (0, validate_1.validateModel)(data);\n return data;\n}\nexports.updateSession = updateSession;\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=session.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateModels = exports.updateLegacySessionModel = exports.validateModel = void 0;\nconst validate_1 = require(\"../kernel/validate\");\nconst validate_2 = require(\"../validate\");\n/**\n * Validate an `Session.IModel` object.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction validateModel(data) {\n (0, validate_2.validateProperty)(data, 'id', 'string');\n (0, validate_2.validateProperty)(data, 'type', 'string');\n (0, validate_2.validateProperty)(data, 'name', 'string');\n (0, validate_2.validateProperty)(data, 'path', 'string');\n (0, validate_2.validateProperty)(data, 'kernel', 'object');\n (0, validate_1.validateModel)(data.kernel);\n}\nexports.validateModel = validateModel;\n/**\n * Update model from legacy session data.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction updateLegacySessionModel(data) {\n if (data.path === undefined && data.notebook !== undefined) {\n data.path = data.notebook.path;\n data.type = 'notebook';\n data.name = '';\n }\n}\nexports.updateLegacySessionModel = updateLegacySessionModel;\n/**\n * Validate an array of `Session.IModel` objects.\n */\nfunction validateModels(models) {\n if (!Array.isArray(models)) {\n throw new Error('Invalid session list');\n }\n models.forEach(d => validateModel(d));\n}\nexports.validateModels = validateModels;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SettingManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst statedb_1 = require(\"@jupyterlab/statedb\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the lab settings service.\n */\nconst SERVICE_SETTINGS_URL = 'api/settings';\n/**\n * The settings API service manager.\n */\nclass SettingManager extends statedb_1.DataConnector {\n /**\n * Create a new setting manager.\n */\n constructor(options = {}) {\n var _a;\n super();\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * Fetch a plugin's settings.\n *\n * @param id - The plugin's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async fetch(id) {\n if (!id) {\n throw new Error('Plugin `id` parameter is required for settings fetch.');\n }\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n // Assert what type the server response is returning.\n return response.json();\n }\n /**\n * Fetch the list of all plugin setting bundles.\n *\n * @returns A promise that resolves if successful.\n */\n async list(query) {\n var _a, _b, _c, _d;\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, '', query === 'ids');\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n throw new ResponseError(response);\n }\n const json = await response.json();\n const ids = (_b = (_a = json === null || json === void 0 ? void 0 : json['settings']) === null || _a === void 0 ? void 0 : _a.map((plugin) => plugin.id)) !== null && _b !== void 0 ? _b : [];\n let values = [];\n if (!query) {\n values =\n (_d = (_c = json === null || json === void 0 ? void 0 : json['settings']) === null || _c === void 0 ? void 0 : _c.map((plugin) => {\n plugin.data = { composite: {}, user: {} };\n return plugin;\n })) !== null && _d !== void 0 ? _d : [];\n }\n return { ids, values };\n }\n /**\n * Save a plugin's settings.\n *\n * @param id - The plugin's ID.\n *\n * @param raw - The user setting values as a raw string of JSON with comments.\n *\n * @returns A promise that resolves if successful.\n */\n async save(id, raw) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n // NOTE: 'raw' is JSON5 (not valid JSON), so we encode it as a string in a valid JSON body\n const init = { body: JSON.stringify({ raw }), method: 'PUT' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n throw new ResponseError(response);\n }\n }\n}\nexports.SettingManager = SettingManager;\n/**\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Get the url for a plugin's settings.\n */\n function url(base, id, idsOnly) {\n const idsOnlyParam = idsOnly\n ? coreutils_1.URLExt.objectToQueryString({ ids_only: true })\n : '';\n return `${coreutils_1.URLExt.join(base, SERVICE_SETTINGS_URL, id)}${idsOnlyParam}`;\n }\n Private.url = url;\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = WebSocket;\n//# sourceMappingURL=ws.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TerminalConnection = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst restapi_1 = require(\"./restapi\");\n/**\n * An implementation of a terminal interface.\n */\nclass TerminalConnection {\n /**\n * Construct a new terminal session.\n */\n constructor(options) {\n var _a;\n /**\n * Create the terminal websocket connection and add socket status handlers.\n *\n * #### Notes\n * You are responsible for updating the connection status as appropriate.\n */\n this._createSocket = () => {\n this._errorIfDisposed();\n // Make sure the socket is clear\n this._clearSocket();\n // Update the connection status to reflect opening a new connection.\n this._updateConnectionStatus('connecting');\n const name = this._name;\n const settings = this.serverSettings;\n let url = coreutils_1.URLExt.join(settings.wsUrl, 'terminals', 'websocket', encodeURIComponent(name));\n // If token authentication is in use.\n const token = settings.token;\n if (settings.appendToken && token !== '') {\n url = url + `?token=${encodeURIComponent(token)}`;\n }\n this._ws = new settings.WebSocket(url);\n this._ws.onmessage = this._onWSMessage;\n this._ws.onclose = this._onWSClose;\n this._ws.onerror = this._onWSClose;\n };\n // Websocket messages events are defined as variables to bind `this`\n this._onWSMessage = (event) => {\n if (this._isDisposed) {\n return;\n }\n const data = JSON.parse(event.data);\n // Handle a disconnect message.\n if (data[0] === 'disconnect') {\n this.dispose();\n }\n if (this._connectionStatus === 'connecting') {\n // After reconnection, ignore all messages until a 'setup' message\n // before we are truly connected. Setting the connection status to\n // connected only then means that if we do not get a setup message\n // before our retry timeout, we will delete the websocket and try again.\n if (data[0] === 'setup') {\n this._updateConnectionStatus('connected');\n }\n return;\n }\n this._messageReceived.emit({\n type: data[0],\n content: data.slice(1)\n });\n };\n this._onWSClose = (event) => {\n console.warn(`Terminal websocket closed: ${event.code}`);\n if (!this.isDisposed) {\n this._reconnect();\n }\n };\n this._connectionStatus = 'connecting';\n this._connectionStatusChanged = new signaling_1.Signal(this);\n this._isDisposed = false;\n this._disposed = new signaling_1.Signal(this);\n this._messageReceived = new signaling_1.Signal(this);\n this._reconnectTimeout = null;\n this._ws = null;\n this._noOp = () => {\n /* no-op */\n };\n this._reconnectLimit = 7;\n this._reconnectAttempt = 0;\n this._pendingMessages = [];\n this._name = options.model.name;\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : __1.ServerConnection.makeSettings();\n this._createSocket();\n }\n /**\n * A signal emitted when the session is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * A signal emitted when a message is received from the server.\n */\n get messageReceived() {\n return this._messageReceived;\n }\n /**\n * Get the name of the terminal session.\n */\n get name() {\n return this._name;\n }\n /**\n * Get the model for the terminal session.\n */\n get model() {\n return { name: this._name };\n }\n /**\n * Test whether the session is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the session.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n this._updateConnectionStatus('disconnected');\n this._clearSocket();\n signaling_1.Signal.clearData(this);\n }\n /**\n * Send a message to the terminal session.\n *\n * #### Notes\n * If the connection is down, the message will be queued for sending when\n * the connection comes back up.\n */\n send(message) {\n this._sendMessage(message);\n }\n /**\n * Send a message on the websocket, or possibly queue for later sending.\n *\n * @param queue - whether to queue the message if it cannot be sent\n */\n _sendMessage(message, queue = true) {\n if (this._isDisposed || !message.content) {\n return;\n }\n if (this.connectionStatus === 'connected' && this._ws) {\n const msg = [message.type, ...message.content];\n this._ws.send(JSON.stringify(msg));\n }\n else if (queue) {\n this._pendingMessages.push(message);\n }\n else {\n throw new Error(`Could not send message: ${JSON.stringify(message)}`);\n }\n }\n /**\n * Send pending messages to the kernel.\n */\n _sendPending() {\n // We check to make sure we are still connected each time. For\n // example, if a websocket buffer overflows, it may close, so we should\n // stop sending messages.\n while (this.connectionStatus === 'connected' &&\n this._pendingMessages.length > 0) {\n this._sendMessage(this._pendingMessages[0], false);\n // We shift the message off the queue after the message is sent so that\n // if there is an exception, the message is still pending.\n this._pendingMessages.shift();\n }\n }\n /**\n * Reconnect to a terminal.\n *\n * #### Notes\n * This may try multiple times to reconnect to a terminal, and will sever\n * any existing connection.\n */\n reconnect() {\n this._errorIfDisposed();\n const result = new coreutils_2.PromiseDelegate();\n // Set up a listener for the connection status changing, which accepts or\n // rejects after the retries are done.\n const fulfill = (sender, status) => {\n if (status === 'connected') {\n result.resolve();\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n else if (status === 'disconnected') {\n result.reject(new Error('Terminal connection disconnected'));\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n };\n this.connectionStatusChanged.connect(fulfill, this);\n // Reset the reconnect limit so we start the connection attempts fresh\n this._reconnectAttempt = 0;\n // Start the reconnection process, which will also clear any existing\n // connection.\n this._reconnect();\n // Return the promise that should resolve on connection or reject if the\n // retries don't work.\n return result.promise;\n }\n /**\n * Attempt a connection if we have not exhausted connection attempts.\n */\n _reconnect() {\n this._errorIfDisposed();\n // Clear any existing reconnection attempt\n clearTimeout(this._reconnectTimeout);\n // Update the connection status and schedule a possible reconnection.\n if (this._reconnectAttempt < this._reconnectLimit) {\n this._updateConnectionStatus('connecting');\n // The first reconnect attempt should happen immediately, and subsequent\n // attempts should pick a random number in a growing range so that we\n // don't overload the server with synchronized reconnection attempts\n // across multiple kernels.\n const timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));\n console.error(`Connection lost, reconnecting in ${Math.floor(timeout / 1000)} seconds.`);\n this._reconnectTimeout = setTimeout(this._createSocket, timeout);\n this._reconnectAttempt += 1;\n }\n else {\n this._updateConnectionStatus('disconnected');\n }\n // Clear the websocket event handlers and the socket itself.\n this._clearSocket();\n }\n /**\n * Forcefully clear the socket state.\n *\n * #### Notes\n * This will clear all socket state without calling any handlers and will\n * not update the connection status. If you call this method, you are\n * responsible for updating the connection status as needed and recreating\n * the socket if you plan to reconnect.\n */\n _clearSocket() {\n if (this._ws !== null) {\n // Clear the websocket event handlers and the socket itself.\n this._ws.onopen = this._noOp;\n this._ws.onclose = this._noOp;\n this._ws.onerror = this._noOp;\n this._ws.onmessage = this._noOp;\n this._ws.close();\n this._ws = null;\n }\n }\n /**\n * Shut down the terminal session.\n */\n async shutdown() {\n await (0, restapi_1.shutdownTerminal)(this.name, this.serverSettings);\n this.dispose();\n }\n /**\n * Clone the current terminal connection.\n */\n clone() {\n return new TerminalConnection(this);\n }\n /**\n * Handle connection status changes.\n */\n _updateConnectionStatus(connectionStatus) {\n if (this._connectionStatus === connectionStatus) {\n return;\n }\n this._connectionStatus = connectionStatus;\n // If we are not 'connecting', stop any reconnection attempts.\n if (connectionStatus !== 'connecting') {\n this._reconnectAttempt = 0;\n clearTimeout(this._reconnectTimeout);\n }\n // Send the pending messages if we just connected.\n if (connectionStatus === 'connected') {\n this._sendPending();\n }\n // Notify others that the connection status changed.\n this._connectionStatusChanged.emit(connectionStatus);\n }\n /**\n * Utility function to throw an error if this instance is disposed.\n */\n _errorIfDisposed() {\n if (this.isDisposed) {\n throw new Error('Terminal connection is disposed');\n }\n }\n /**\n * A signal emitted when the terminal connection status changes.\n */\n get connectionStatusChanged() {\n return this._connectionStatusChanged;\n }\n /**\n * The current connection status of the terminal connection.\n */\n get connectionStatus() {\n return this._connectionStatus;\n }\n}\nexports.TerminalConnection = TerminalConnection;\nvar Private;\n(function (Private) {\n /**\n * Get the url for a terminal.\n */\n function getTermUrl(baseUrl, name) {\n return coreutils_1.URLExt.join(baseUrl, restapi_1.TERMINAL_SERVICE_URL, encodeURIComponent(name));\n }\n Private.getTermUrl = getTermUrl;\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n Private.getRandomIntInclusive = getRandomIntInclusive;\n})(Private || (Private = {}));\n//# sourceMappingURL=default.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TerminalAPI = exports.Terminal = void 0;\nconst Terminal = __importStar(require(\"./terminal\"));\nexports.Terminal = Terminal;\nconst TerminalAPI = __importStar(require(\"./restapi\"));\nexports.TerminalAPI = TerminalAPI;\n__exportStar(require(\"./manager\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TerminalManager = void 0;\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst __1 = require(\"..\");\nconst basemanager_1 = require(\"../basemanager\");\nconst restapi_1 = require(\"./restapi\");\nconst default_1 = require(\"./default\");\n/**\n * A terminal session manager.\n */\nclass TerminalManager extends basemanager_1.BaseManager {\n /**\n * Construct a new terminal manager.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n // As an optimization, we unwrap the models to just store the names.\n this._names = [];\n this._terminalConnections = new Set();\n this._runningChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // Check if terminals are available\n if (!this.isAvailable()) {\n this._ready = Promise.reject('Terminals unavailable');\n this._ready.catch(_ => undefined);\n return;\n }\n // Start polling with exponential backoff.\n this._pollModels = new polling_1.Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:TerminalManager#models`,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n this._isReady = true;\n })();\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * A signal emitted when the running terminals change.\n */\n get runningChanged() {\n return this._runningChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._names.length = 0;\n this._terminalConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n /**\n * Whether the terminal service is available.\n */\n isAvailable() {\n return (0, restapi_1.isAvailable)();\n }\n /*\n * Connect to a running terminal.\n *\n * @param options - The options used to connect to the terminal.\n *\n * @returns The new terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be used.\n */\n connectTo(options) {\n const terminalConnection = new default_1.TerminalConnection({\n ...options,\n serverSettings: this.serverSettings\n });\n this._onStarted(terminalConnection);\n if (!this._names.includes(options.model.name)) {\n // We trust the user to connect to an existing session, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return terminalConnection;\n }\n /**\n * Create an iterator over the most recent running terminals.\n *\n * @returns A new iterator over the running terminals.\n */\n running() {\n return this._models[Symbol.iterator]();\n }\n /**\n * Force a refresh of the running terminals.\n *\n * @returns A promise that with the list of running terminals.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshRunning() {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n /**\n * Create a new terminal session.\n *\n * @param options - The options used to create the terminal.\n *\n * @returns A promise that resolves with the terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be used unless overridden in the\n * options.\n */\n async startNew(options) {\n const model = await (0, restapi_1.startNew)(this.serverSettings, options === null || options === void 0 ? void 0 : options.name, options === null || options === void 0 ? void 0 : options.cwd);\n await this.refreshRunning();\n return this.connectTo({ model });\n }\n /**\n * Shut down a terminal session by name.\n */\n async shutdown(name) {\n await (0, restapi_1.shutdownTerminal)(name, this.serverSettings);\n await this.refreshRunning();\n }\n /**\n * Shut down all terminal sessions.\n *\n * @returns A promise that resolves when all of the sessions are shut down.\n */\n async shutdownAll() {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n // Shut down all models.\n await Promise.all(this._names.map(name => (0, restapi_1.shutdownTerminal)(name, this.serverSettings)));\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n /**\n * Execute a request to the server to poll running terminals and update state.\n */\n async requestRunning() {\n var _a, _b;\n let models;\n try {\n models = await (0, restapi_1.listRunning)(this.serverSettings);\n }\n catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (err instanceof __1.ServerConnection.NetworkError ||\n ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 503 ||\n ((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) === 424) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n if (this.isDisposed) {\n return;\n }\n const names = models.map(({ name }) => name).sort();\n if (names === this._names) {\n // Identical models list, so just return\n return;\n }\n this._names = names;\n this._terminalConnections.forEach(tc => {\n if (!names.includes(tc.name)) {\n tc.dispose();\n }\n });\n this._runningChanged.emit(this._models);\n }\n /**\n * Handle a session starting.\n */\n _onStarted(terminalConnection) {\n this._terminalConnections.add(terminalConnection);\n terminalConnection.disposed.connect(this._onDisposed, this);\n }\n /**\n * Handle a session terminating.\n */\n _onDisposed(terminalConnection) {\n this._terminalConnections.delete(terminalConnection);\n // Update the running models to make sure we reflect the server state\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n get _models() {\n return this._names.map(name => {\n return { name };\n });\n }\n}\nexports.TerminalManager = TerminalManager;\n/**\n * The namespace for TerminalManager statics.\n */\n(function (TerminalManager) {\n /**\n * A no-op terminal manager to be used when starting terminals is not supported.\n */\n class NoopManager extends TerminalManager {\n constructor() {\n super(...arguments);\n this._readyPromise = new Promise(() => {\n /* no-op */\n });\n }\n /**\n * Whether the manager is active.\n */\n get isActive() {\n return false;\n }\n /**\n * Used for testing.\n */\n get parentReady() {\n return super.ready;\n }\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready() {\n return this.parentReady.then(() => this._readyPromise);\n }\n /**\n * Create a new terminal session - throw an error since it is not supported.\n *\n */\n async startNew(options) {\n return Promise.reject(new Error('Not implemented in no-op Terminal Manager'));\n }\n /*\n * Connect to a running terminal - throw an error since it is not supported.\n */\n connectTo(options) {\n throw Error('Not implemented in no-op Terminal Manager');\n }\n /**\n * Shut down a session by id - throw an error since it is not supported.\n */\n async shutdown(id) {\n return Promise.reject(new Error('Not implemented in no-op Terminal Manager'));\n }\n /**\n * Execute a request to the server to poll running sessions and update state.\n */\n async requestRunning() {\n return Promise.resolve();\n }\n }\n TerminalManager.NoopManager = NoopManager;\n})(TerminalManager = exports.TerminalManager || (exports.TerminalManager = {}));\n//# sourceMappingURL=manager.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shutdownTerminal = exports.listRunning = exports.startNew = exports.isAvailable = exports.TERMINAL_SERVICE_URL = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the terminal service.\n */\nexports.TERMINAL_SERVICE_URL = 'api/terminals';\n/**\n * Whether the terminal service is available.\n */\nfunction isAvailable() {\n const available = String(coreutils_1.PageConfig.getOption('terminalsAvailable'));\n return available.toLowerCase() === 'true';\n}\nexports.isAvailable = isAvailable;\n/**\n * Start a new terminal session.\n *\n * @param settings - The server settings to use.\n *\n * @param name - The name of the target terminal.\n *\n * @param cwd - The path in which the terminal will start.\n *\n * @returns A promise that resolves with the session model.\n */\nasync function startNew(settings = serverconnection_1.ServerConnection.makeSettings(), name, cwd) {\n Private.errorIfNotAvailable();\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify({ name, cwd })\n };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n // TODO: Validate model\n return data;\n}\nexports.startNew = startNew;\n/**\n * List the running terminal sessions.\n *\n * @param settings - The server settings to use.\n *\n * @returns A promise that resolves with the list of running session models.\n */\nasync function listRunning(settings = serverconnection_1.ServerConnection.makeSettings()) {\n Private.errorIfNotAvailable();\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL);\n const response = await serverconnection_1.ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid terminal list');\n }\n // TODO: validate each model\n return data;\n}\nexports.listRunning = listRunning;\n/**\n * Shut down a terminal session by name.\n *\n * @param name - The name of the target session.\n *\n * @param settings - The server settings to use.\n *\n * @returns A promise that resolves when the session is shut down.\n */\nasync function shutdownTerminal(name, settings = serverconnection_1.ServerConnection.makeSettings()) {\n var _a;\n Private.errorIfNotAvailable();\n const url = coreutils_1.URLExt.join(settings.baseUrl, exports.TERMINAL_SERVICE_URL, name);\n const init = { method: 'DELETE' };\n const response = await serverconnection_1.ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const data = await response.json();\n const msg = (_a = data.message) !== null && _a !== void 0 ? _a : `The terminal session \"${name}\"\" does not exist on the server`;\n console.warn(msg);\n }\n else if (response.status !== 204) {\n const err = await serverconnection_1.ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\nexports.shutdownTerminal = shutdownTerminal;\nvar Private;\n(function (Private) {\n /**\n * Throw an error if terminals are not available.\n */\n function errorIfNotAvailable() {\n if (!isAvailable()) {\n throw new Error('Terminals Unavailable');\n }\n }\n Private.errorIfNotAvailable = errorIfNotAvailable;\n})(Private || (Private = {}));\n//# sourceMappingURL=restapi.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAvailable = void 0;\nconst restapi_1 = require(\"./restapi\");\nObject.defineProperty(exports, \"isAvailable\", { enumerable: true, get: function () { return restapi_1.isAvailable; } });\n//# sourceMappingURL=terminal.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UserManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst coreutils_2 = require(\"@lumino/coreutils\");\nconst polling_1 = require(\"@lumino/polling\");\nconst signaling_1 = require(\"@lumino/signaling\");\nconst serverconnection_1 = require(\"../serverconnection\");\nconst basemanager_1 = require(\"../basemanager\");\n/**\n * The url for the lab workspaces service.\n */\nconst SERVICE_USER_URL = 'api/me';\n/**\n * The service's ID.\n * Used to uniquely identify the poll, and\n * the item in local storage.\n */\nconst SERVICE_ID = '@jupyterlab/services:UserManager#user';\n/**\n * The user API service manager.\n */\nclass UserManager extends basemanager_1.BaseManager {\n /**\n * Create a new user manager.\n */\n constructor(options = {}) {\n var _a;\n super(options);\n this._isReady = false;\n this._userChanged = new signaling_1.Signal(this);\n this._connectionFailure = new signaling_1.Signal(this);\n // Initialize internal data.\n this._ready = this.requestUser()\n .then(() => {\n if (this.isDisposed) {\n return;\n }\n this._isReady = true;\n })\n .catch(_ => \n // Return a promise that will never resolve, so user service is never ready\n // This typically occurs when the backend has no user service\n new Promise(() => {\n // no-op\n }));\n this._pollSpecs = new polling_1.Poll({\n auto: false,\n factory: () => this.requestUser(),\n frequency: {\n interval: 61 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: SERVICE_ID,\n standby: (_a = options.standby) !== null && _a !== void 0 ? _a : 'when-hidden'\n });\n void this.ready.then(() => {\n void this._pollSpecs.start();\n });\n }\n /**\n * Test whether the manager is ready.\n */\n get isReady() {\n return this._isReady;\n }\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready() {\n return this._ready;\n }\n /**\n * Get the most recently fetched identity.\n */\n get identity() {\n return this._identity;\n }\n /**\n * Get the most recently fetched permissions.\n */\n get permissions() {\n return this._permissions;\n }\n /**\n * A signal emitted when the user changes.\n */\n get userChanged() {\n return this._userChanged;\n }\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure() {\n return this._connectionFailure;\n }\n /**\n * Dispose of the resources used by the manager.\n */\n dispose() {\n this._pollSpecs.dispose();\n super.dispose();\n }\n /**\n * Force a refresh of the specs from the server.\n *\n * @returns A promise that resolves when the specs are fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshUser() {\n await this._pollSpecs.refresh();\n await this._pollSpecs.tick;\n }\n /**\n * Execute a request to the server to poll the user and update state.\n */\n async requestUser() {\n if (this.isDisposed) {\n return;\n }\n const { baseUrl } = this.serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const url = coreutils_1.URLExt.join(baseUrl, SERVICE_USER_URL);\n const response = await makeRequest(url, {}, this.serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n const oldUser = {\n identity: this._identity,\n permissions: this._permissions\n };\n const newUser = await response.json();\n const identity = newUser.identity;\n // store the color and initials for the user\n // this info is not provided by the server\n const { localStorage } = window;\n const data = localStorage.getItem(SERVICE_ID);\n if (data && (!identity.initials || !identity.color)) {\n const localUser = JSON.parse(data);\n identity.initials =\n identity.initials ||\n localUser.initials ||\n identity.name.substring(0, 1);\n identity.color =\n identity.color || localUser.color || Private.getRandomColor();\n }\n if (!coreutils_2.JSONExt.deepEqual(newUser, oldUser)) {\n this._identity = identity;\n this._permissions = newUser.permissions;\n localStorage.setItem(SERVICE_ID, JSON.stringify(identity));\n this._userChanged.emit(newUser);\n }\n }\n}\nexports.UserManager = UserManager;\n/**\n * A namespace for module-private functionality.\n *\n * Note: We do not want to export this function\n * to move it to css variables in the Theme.\n */\nvar Private;\n(function (Private) {\n /**\n * Predefined colors for users\n */\n const userColors = [\n 'var(--jp-collaborator-color1)',\n 'var(--jp-collaborator-color2)',\n 'var(--jp-collaborator-color3)',\n 'var(--jp-collaborator-color4)',\n 'var(--jp-collaborator-color5)',\n 'var(--jp-collaborator-color6)',\n 'var(--jp-collaborator-color7)'\n ];\n /**\n * Get a random color from the list of colors.\n */\n Private.getRandomColor = () => userColors[Math.floor(Math.random() * userColors.length)];\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.validateProperty = void 0;\n/**\n * Validate a property as being on an object, and optionally\n * of a given type and among a given set of values.\n */\nfunction validateProperty(\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nobject, name, typeName, values = []) {\n if (!object.hasOwnProperty(name)) {\n throw Error(`Missing property '${name}'`);\n }\n const value = object[name];\n if (typeName !== void 0) {\n let valid = true;\n switch (typeName) {\n case 'array':\n valid = Array.isArray(value);\n break;\n case 'object':\n valid = typeof value !== 'undefined';\n break;\n default:\n valid = typeof value === typeName;\n }\n if (!valid) {\n throw new Error(`Property '${name}' is not of type '${typeName}'`);\n }\n if (values.length > 0) {\n let valid = true;\n switch (typeName) {\n case 'string':\n case 'number':\n case 'boolean':\n valid = values.includes(value);\n break;\n default:\n valid = values.findIndex(v => v === value) >= 0;\n break;\n }\n if (!valid) {\n throw new Error(`Property '${name}' is not one of the valid values ${JSON.stringify(values)}`);\n }\n }\n }\n}\nexports.validateProperty = validateProperty;\n//# sourceMappingURL=validate.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.WorkspaceManager = void 0;\nconst coreutils_1 = require(\"@jupyterlab/coreutils\");\nconst statedb_1 = require(\"@jupyterlab/statedb\");\nconst serverconnection_1 = require(\"../serverconnection\");\n/**\n * The url for the lab workspaces service.\n */\nconst SERVICE_WORKSPACES_URL = 'api/workspaces';\n/**\n * The workspaces API service manager.\n */\nclass WorkspaceManager extends statedb_1.DataConnector {\n /**\n * Create a new workspace manager.\n */\n constructor(options = {}) {\n var _a;\n super();\n this.serverSettings =\n (_a = options.serverSettings) !== null && _a !== void 0 ? _a : serverconnection_1.ServerConnection.makeSettings();\n }\n /**\n * Fetch a workspace.\n *\n * @param id - The workspace's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async fetch(id) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n return response.json();\n }\n /**\n * Fetch the list of workspace IDs that exist on the server.\n *\n * @returns A promise that resolves if successful.\n */\n async list() {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, '');\n const response = await makeRequest(url, {}, serverSettings);\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n const result = await response.json();\n return result.workspaces;\n }\n /**\n * Remove a workspace from the server.\n *\n * @param id - The workspaces's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async remove(id) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const init = { method: 'DELETE' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n const err = await ResponseError.create(response);\n throw err;\n }\n }\n /**\n * Save a workspace.\n *\n * @param id - The workspace's ID.\n *\n * @param workspace - The workspace being saved.\n *\n * @returns A promise that resolves if successful.\n */\n async save(id, workspace) {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = serverconnection_1.ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const init = { body: JSON.stringify(workspace), method: 'PUT' };\n const response = await makeRequest(url, init, serverSettings);\n if (response.status !== 204) {\n const err = await ResponseError.create(response);\n throw err;\n }\n }\n}\nexports.WorkspaceManager = WorkspaceManager;\n/**\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * Get the url for a workspace.\n */\n function url(base, id) {\n return coreutils_1.URLExt.join(base, SERVICE_WORKSPACES_URL, id);\n }\n Private.url = url;\n})(Private || (Private = {}));\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ActivityMonitor = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * A class that monitors activity on a signal.\n */\nclass ActivityMonitor {\n /**\n * Construct a new activity monitor.\n */\n constructor(options) {\n this._timer = -1;\n this._timeout = -1;\n this._isDisposed = false;\n this._activityStopped = new signaling_1.Signal(this);\n options.signal.connect(this._onSignalFired, this);\n this._timeout = options.timeout || 1000;\n }\n /**\n * A signal emitted when activity has ceased.\n */\n get activityStopped() {\n return this._activityStopped;\n }\n /**\n * The timeout associated with the monitor, in milliseconds.\n */\n get timeout() {\n return this._timeout;\n }\n set timeout(value) {\n this._timeout = value;\n }\n /**\n * Test whether the monitor has been disposed.\n *\n * #### Notes\n * This is a read-only property.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources used by the activity monitor.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * A signal handler for the monitored signal.\n */\n _onSignalFired(sender, args) {\n clearTimeout(this._timer);\n this._sender = sender;\n this._args = args;\n this._timer = setTimeout(() => {\n this._activityStopped.emit({\n sender: this._sender,\n args: this._args\n });\n }, this._timeout);\n }\n}\nexports.ActivityMonitor = ActivityMonitor;\n//# sourceMappingURL=activitymonitor.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module coreutils\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./activitymonitor\"), exports);\n__exportStar(require(\"./interfaces\"), exports);\n__exportStar(require(\"./markdowncodeblocks\"), exports);\n__exportStar(require(\"./pageconfig\"), exports);\n__exportStar(require(\"./path\"), exports);\n__exportStar(require(\"./signal\"), exports);\n__exportStar(require(\"./text\"), exports);\n__exportStar(require(\"./time\"), exports);\n__exportStar(require(\"./url\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=interfaces.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MarkdownCodeBlocks = void 0;\n/**\n * The namespace for code block functions which help\n * in extract code from markdown text\n */\nvar MarkdownCodeBlocks;\n(function (MarkdownCodeBlocks) {\n MarkdownCodeBlocks.CODE_BLOCK_MARKER = '```';\n const markdownExtensions = [\n '.markdown',\n '.mdown',\n '.mkdn',\n '.md',\n '.mkd',\n '.mdwn',\n '.mdtxt',\n '.mdtext',\n '.text',\n '.txt',\n '.Rmd'\n ];\n class MarkdownCodeBlock {\n constructor(startLine) {\n this.startLine = startLine;\n this.code = '';\n this.endLine = -1;\n }\n }\n MarkdownCodeBlocks.MarkdownCodeBlock = MarkdownCodeBlock;\n /**\n * Check whether the given file extension is a markdown extension\n * @param extension - A file extension\n *\n * @returns true/false depending on whether this is a supported markdown extension\n */\n function isMarkdown(extension) {\n return markdownExtensions.indexOf(extension) > -1;\n }\n MarkdownCodeBlocks.isMarkdown = isMarkdown;\n /**\n * Construct all code snippets from current text\n * (this could be potentially optimized if we can cache and detect differences)\n * @param text - A string to parse codeblocks from\n *\n * @returns An array of MarkdownCodeBlocks.\n */\n function findMarkdownCodeBlocks(text) {\n if (!text || text === '') {\n return [];\n }\n const lines = text.split('\\n');\n const codeBlocks = [];\n let currentBlock = null;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n const lineContainsMarker = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER) === 0;\n const constructingBlock = currentBlock != null;\n // Skip this line if it is not part of any code block and doesn't contain a marker.\n if (!lineContainsMarker && !constructingBlock) {\n continue;\n }\n // Check if we are already constructing a code block.\n if (!constructingBlock) {\n // Start constructing a new code block.\n currentBlock = new MarkdownCodeBlock(lineIndex);\n // Check whether this is a single line code block of the form ```a = 10```.\n const firstIndex = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const lastIndex = line.lastIndexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const isSingleLine = firstIndex !== lastIndex;\n if (isSingleLine) {\n currentBlock.code = line.substring(firstIndex + MarkdownCodeBlocks.CODE_BLOCK_MARKER.length, lastIndex);\n currentBlock.endLine = lineIndex;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n }\n else if (currentBlock) {\n if (lineContainsMarker) {\n // End of block, finish it up.\n currentBlock.endLine = lineIndex - 1;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n else {\n // Append the current line.\n currentBlock.code += line + '\\n';\n }\n }\n }\n return codeBlocks;\n }\n MarkdownCodeBlocks.findMarkdownCodeBlocks = findMarkdownCodeBlocks;\n})(MarkdownCodeBlocks = exports.MarkdownCodeBlocks || (exports.MarkdownCodeBlocks = {}));\n//# sourceMappingURL=markdowncodeblocks.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PageConfig = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst minimist_1 = __importDefault(require(\"minimist\"));\nconst url_1 = require(\"./url\");\n/**\n * The namespace for `PageConfig` functions.\n */\nvar PageConfig;\n(function (PageConfig) {\n /**\n * Get global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n *\n * @returns The config value or an empty string if not found.\n *\n * #### Notes\n * All values are treated as strings.\n * For browser based applications, it is assumed that the page HTML\n * includes a script tag with the id `jupyter-config-data` containing the\n * configuration as valid JSON. In order to support the classic Notebook,\n * we fall back on checking for `body` data of the given `name`.\n *\n * For node applications, it is assumed that the process was launched\n * with a `--jupyter-config-data` option pointing to a JSON settings\n * file.\n */\n function getOption(name) {\n if (configData) {\n return configData[name] || getBodyData(name);\n }\n configData = Object.create(null);\n let found = false;\n // Use script tag if available.\n if (typeof document !== 'undefined' && document) {\n const el = document.getElementById('jupyter-config-data');\n if (el) {\n configData = JSON.parse(el.textContent || '');\n found = true;\n }\n }\n // Otherwise use CLI if given.\n if (!found && typeof process !== 'undefined' && process.argv) {\n try {\n const cli = (0, minimist_1.default)(process.argv.slice(2));\n const path = require('path');\n let fullPath = '';\n if ('jupyter-config-data' in cli) {\n fullPath = path.resolve(cli['jupyter-config-data']);\n }\n else if ('JUPYTER_CONFIG_DATA' in process.env) {\n fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);\n }\n if (fullPath) {\n // Force Webpack to ignore this require.\n // eslint-disable-next-line\n configData = eval('require')(fullPath);\n }\n }\n catch (e) {\n console.error(e);\n }\n }\n if (!coreutils_1.JSONExt.isObject(configData)) {\n configData = Object.create(null);\n }\n else {\n for (const key in configData) {\n // PageConfig expects strings\n if (typeof configData[key] !== 'string') {\n configData[key] = JSON.stringify(configData[key]);\n }\n }\n }\n return configData[name] || getBodyData(name);\n }\n PageConfig.getOption = getOption;\n /**\n * Set global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n * @param value - The value to set the option to.\n *\n * @returns The last config value or an empty string if it doesn't exist.\n */\n function setOption(name, value) {\n const last = getOption(name);\n configData[name] = value;\n return last;\n }\n PageConfig.setOption = setOption;\n /**\n * Get the base url for a Jupyter application, or the base url of the page.\n */\n function getBaseUrl() {\n return url_1.URLExt.normalize(getOption('baseUrl') || '/');\n }\n PageConfig.getBaseUrl = getBaseUrl;\n /**\n * Get the tree url for a JupyterLab application.\n */\n function getTreeUrl() {\n return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }\n PageConfig.getTreeUrl = getTreeUrl;\n /**\n * Get the base url for sharing links (usually baseUrl)\n */\n function getShareUrl() {\n return url_1.URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }\n PageConfig.getShareUrl = getShareUrl;\n /**\n * Get the tree url for shareable links.\n * Usually the same as treeUrl,\n * but overrideable e.g. when sharing with JupyterHub.\n */\n function getTreeShareUrl() {\n return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(), getOption('treeUrl')));\n }\n PageConfig.getTreeShareUrl = getTreeShareUrl;\n /**\n * Create a new URL given an optional mode and tree path.\n *\n * This is used to create URLS when the mode or tree path change as the user\n * changes mode or the current document in the main area. If fields in\n * options are omitted, the value in PageConfig will be used.\n *\n * @param options - IGetUrlOptions for the new path.\n */\n function getUrl(options) {\n var _a, _b, _c, _d;\n let path = options.toShare ? getShareUrl() : getBaseUrl();\n const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : getOption('mode');\n const workspace = (_b = options.workspace) !== null && _b !== void 0 ? _b : getOption('workspace');\n const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';\n path = url_1.URLExt.join(path, labOrDoc);\n if (workspace !== PageConfig.defaultWorkspace) {\n path = url_1.URLExt.join(path, 'workspaces', encodeURIComponent((_c = getOption('workspace')) !== null && _c !== void 0 ? _c : PageConfig.defaultWorkspace));\n }\n const treePath = (_d = options.treePath) !== null && _d !== void 0 ? _d : getOption('treePath');\n if (treePath) {\n path = url_1.URLExt.join(path, 'tree', url_1.URLExt.encodeParts(treePath));\n }\n return path;\n }\n PageConfig.getUrl = getUrl;\n PageConfig.defaultWorkspace = 'default';\n /**\n * Get the base websocket url for a Jupyter application, or an empty string.\n */\n function getWsUrl(baseUrl) {\n let wsUrl = getOption('wsUrl');\n if (!wsUrl) {\n baseUrl = baseUrl ? url_1.URLExt.normalize(baseUrl) : getBaseUrl();\n if (baseUrl.indexOf('http') !== 0) {\n return '';\n }\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n return url_1.URLExt.normalize(wsUrl);\n }\n PageConfig.getWsUrl = getWsUrl;\n /**\n * Returns the URL converting this notebook to a certain\n * format with nbconvert.\n */\n function getNBConvertURL({ path, format, download }) {\n const notebookPath = url_1.URLExt.encodeParts(path);\n const url = url_1.URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);\n if (download) {\n return url + '?download=true';\n }\n return url;\n }\n PageConfig.getNBConvertURL = getNBConvertURL;\n /**\n * Get the authorization token for a Jupyter application.\n */\n function getToken() {\n return getOption('token') || getBodyData('jupyterApiToken');\n }\n PageConfig.getToken = getToken;\n /**\n * Get the Notebook version info [major, minor, patch].\n */\n function getNotebookVersion() {\n const notebookVersion = getOption('notebookVersion');\n if (notebookVersion === '') {\n return [0, 0, 0];\n }\n return JSON.parse(notebookVersion);\n }\n PageConfig.getNotebookVersion = getNotebookVersion;\n /**\n * Private page config data for the Jupyter application.\n */\n let configData = null;\n /**\n * Get a url-encoded item from `body.data` and decode it\n * We should never have any encoded URLs anywhere else in code\n * until we are building an actual request.\n */\n function getBodyData(key) {\n if (typeof document === 'undefined' || !document.body) {\n return '';\n }\n const val = document.body.dataset[key];\n if (typeof val === 'undefined') {\n return '';\n }\n return decodeURIComponent(val);\n }\n /**\n * The namespace for page config `Extension` functions.\n */\n let Extension;\n (function (Extension) {\n /**\n * Populate an array from page config.\n *\n * @param key - The page config key (e.g., `deferredExtensions`).\n *\n * #### Notes\n * This is intended for `deferredExtensions` and `disabledExtensions`.\n */\n function populate(key) {\n try {\n const raw = getOption(key);\n if (raw) {\n return JSON.parse(raw);\n }\n }\n catch (error) {\n console.warn(`Unable to parse ${key}.`, error);\n }\n return [];\n }\n /**\n * The collection of deferred extensions in page config.\n */\n Extension.deferred = populate('deferredExtensions');\n /**\n * The collection of disabled extensions in page config.\n */\n Extension.disabled = populate('disabledExtensions');\n /**\n * Returns whether a plugin is deferred.\n *\n * @param id - The plugin ID.\n */\n function isDeferred(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.deferred.some(val => val === id || (extName && val === extName));\n }\n Extension.isDeferred = isDeferred;\n /**\n * Returns whether a plugin is disabled.\n *\n * @param id - The plugin ID.\n */\n function isDisabled(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.disabled.some(val => val === id || (extName && val === extName));\n }\n Extension.isDisabled = isDisabled;\n })(Extension = PageConfig.Extension || (PageConfig.Extension = {}));\n})(PageConfig = exports.PageConfig || (exports.PageConfig = {}));\n//# sourceMappingURL=pageconfig.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PathExt = void 0;\nconst path_1 = require(\"path\");\n/**\n * The namespace for path-related functions.\n *\n * Note that Jupyter server paths do not start with a leading slash.\n */\nvar PathExt;\n(function (PathExt) {\n /**\n * Join all arguments together and normalize the resulting path.\n * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n *\n * @param paths - The string paths to join.\n */\n function join(...paths) {\n const path = path_1.posix.join(...paths);\n return path === '.' ? '' : removeSlash(path);\n }\n PathExt.join = join;\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * Often used to extract the file name from a fully qualified path.\n *\n * @param path - The path to evaluate.\n *\n * @param ext - An extension to remove from the result.\n */\n function basename(path, ext) {\n return path_1.posix.basename(path, ext);\n }\n PathExt.basename = basename;\n /**\n * Get the directory name of a path, similar to the Unix dirname command.\n * When an empty path is given, returns the root path.\n *\n * @param path - The file path.\n */\n function dirname(path) {\n const dir = removeSlash(path_1.posix.dirname(path));\n return dir === '.' ? '' : dir;\n }\n PathExt.dirname = dirname;\n /**\n * Get the extension of the path.\n *\n * @param path - The file path.\n *\n * @returns the extension of the file.\n *\n * #### Notes\n * The extension is the string from the last occurrence of the `.`\n * character to end of string in the last portion of the path, inclusive.\n * If there is no `.` in the last portion of the path, or if the first\n * character of the basename of path [[basename]] is `.`, then an\n * empty string is returned.\n */\n function extname(path) {\n return path_1.posix.extname(path);\n }\n PathExt.extname = extname;\n /**\n * Normalize a string path, reducing '..' and '.' parts.\n * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n * When an empty path is given, returns the root path.\n *\n * @param path - The string path to normalize.\n */\n function normalize(path) {\n if (path === '') {\n return '';\n }\n return removeSlash(path_1.posix.normalize(path));\n }\n PathExt.normalize = normalize;\n /**\n * Resolve a sequence of paths or path segments into an absolute path.\n * The root path in the application has no leading slash, so it is removed.\n *\n * @param parts - The paths to join.\n *\n * #### Notes\n * The right-most parameter is considered \\{to\\}. Other parameters are considered an array of \\{from\\}.\n *\n * Starting from leftmost \\{from\\} parameter, resolves \\{to\\} to an absolute path.\n *\n * If \\{to\\} isn't already absolute, \\{from\\} arguments are prepended in right to left order, until an absolute path is found. If after using all \\{from\\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n */\n function resolve(...parts) {\n return removeSlash(path_1.posix.resolve(...parts));\n }\n PathExt.resolve = resolve;\n /**\n * Solve the relative path from \\{from\\} to \\{to\\}.\n *\n * @param from - The source path.\n *\n * @param to - The target path.\n *\n * #### Notes\n * If from and to each resolve to the same path (after calling\n * path.resolve() on each), a zero-length string is returned.\n * If a zero-length string is passed as from or to, `/`\n * will be used instead of the zero-length strings.\n */\n function relative(from, to) {\n return removeSlash(path_1.posix.relative(from, to));\n }\n PathExt.relative = relative;\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * @param extension - the file extension.\n *\n * #### Notes\n * Adds a leading dot if not present and converts to lower case.\n */\n function normalizeExtension(extension) {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n PathExt.normalizeExtension = normalizeExtension;\n /**\n * Remove the leading slash from a path.\n *\n * @param path: the path from which to remove a leading slash.\n */\n function removeSlash(path) {\n if (path.indexOf('/') === 0) {\n path = path.slice(1);\n }\n return path;\n }\n PathExt.removeSlash = removeSlash;\n})(PathExt = exports.PathExt || (exports.PathExt = {}));\n//# sourceMappingURL=path.js.map","\"use strict\";\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.signalToPromise = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * Convert a signal into a promise for the first emitted value.\n *\n * @param signal - The signal we are listening to.\n * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)\n *\n * @returns a Promise that resolves with a `(sender, args)` pair.\n */\nfunction signalToPromise(signal, timeout) {\n const waitForSignal = new coreutils_1.PromiseDelegate();\n function cleanup() {\n signal.disconnect(slot);\n }\n function slot(sender, args) {\n cleanup();\n waitForSignal.resolve([sender, args]);\n }\n signal.connect(slot);\n if ((timeout !== null && timeout !== void 0 ? timeout : 0) > 0) {\n setTimeout(() => {\n cleanup();\n waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);\n }, timeout);\n }\n return waitForSignal.promise;\n}\nexports.signalToPromise = signalToPromise;\n//# sourceMappingURL=signal.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Text = void 0;\n/**\n * The namespace for text-related functions.\n */\nvar Text;\n(function (Text) {\n // javascript stores text as utf16 and string indices use \"code units\",\n // which stores high-codepoint characters as \"surrogate pairs\",\n // which occupy two indices in the javascript string.\n // We need to translate cursor_pos in the Jupyter protocol (in characters)\n // to js offset (with surrogate pairs taking two spots).\n const HAS_SURROGATES = '𝐚'.length > 1;\n /**\n * Convert a javascript string index into a unicode character offset\n *\n * @param jsIdx - The javascript string index (counting surrogate pairs)\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The unicode character offset\n */\n function jsIndexToCharIndex(jsIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return jsIdx;\n }\n let charIdx = jsIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n charIdx--;\n i++;\n }\n }\n }\n return charIdx;\n }\n Text.jsIndexToCharIndex = jsIndexToCharIndex;\n /**\n * Convert a unicode character offset to a javascript string index.\n *\n * @param charIdx - The index in unicode characters\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The js-native index\n */\n function charIndexToJsIndex(charIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return charIdx;\n }\n let jsIdx = charIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n jsIdx++;\n i++;\n }\n }\n }\n return jsIdx;\n }\n Text.charIndexToJsIndex = charIndexToJsIndex;\n /**\n * Given a 'snake-case', 'snake_case', 'snake:case', or\n * 'snake case' string, will return the camel case version: 'snakeCase'.\n *\n * @param str: the snake-case input string.\n *\n * @param upper: default = false. If true, the first letter of the\n * returned string will be capitalized.\n *\n * @returns the camel case version of the input string.\n */\n function camelCase(str, upper = false) {\n return str.replace(/^(\\w)|[\\s-_:]+(\\w)/g, function (match, p1, p2) {\n if (p2) {\n return p2.toUpperCase();\n }\n else {\n return upper ? p1.toUpperCase() : p1.toLowerCase();\n }\n });\n }\n Text.camelCase = camelCase;\n /**\n * Given a string, title case the words in the string.\n *\n * @param str: the string to title case.\n *\n * @returns the same string, but with each word capitalized.\n */\n function titleCase(str) {\n return (str || '')\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n Text.titleCase = titleCase;\n})(Text = exports.Text || (exports.Text = {}));\n//# sourceMappingURL=text.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Time = void 0;\n/**\n * A list of time units with their associated value in milliseconds.\n */\nconst UNITS = [\n { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },\n { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },\n { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },\n { name: 'hours', milliseconds: 60 * 60 * 1000 },\n { name: 'minutes', milliseconds: 60 * 1000 },\n { name: 'seconds', milliseconds: 1000 }\n];\n/**\n * The namespace for date functions.\n */\nvar Time;\n(function (Time) {\n /**\n * Convert a timestring to a human readable string (e.g. 'two minutes ago').\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function formatHuman(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' });\n const delta = new Date(value).getTime() - Date.now();\n for (let unit of UNITS) {\n const amount = Math.ceil(delta / unit.milliseconds);\n if (amount === 0) {\n continue;\n }\n return formatter.format(amount, unit.name);\n }\n return formatter.format(0, 'seconds');\n }\n Time.formatHuman = formatHuman;\n /**\n * Convenient helper to convert a timestring to a date format.\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function format(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.DateTimeFormat(lang, {\n dateStyle: 'short',\n timeStyle: 'short'\n });\n return formatter.format(new Date(value));\n }\n Time.format = format;\n})(Time = exports.Time || (exports.Time = {}));\n//# sourceMappingURL=time.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URLExt = void 0;\nconst path_1 = require(\"path\");\nconst url_parse_1 = __importDefault(require(\"url-parse\"));\n/**\n * The namespace for URL-related functions.\n */\nvar URLExt;\n(function (URLExt) {\n /**\n * Parse a url into a URL object.\n *\n * @param urlString - The URL string to parse.\n *\n * @returns A URL object.\n */\n function parse(url) {\n if (typeof document !== 'undefined' && document) {\n const a = document.createElement('a');\n a.href = url;\n return a;\n }\n return (0, url_parse_1.default)(url);\n }\n URLExt.parse = parse;\n /**\n * Parse URL and retrieve hostname\n *\n * @param url - The URL string to parse\n *\n * @returns a hostname string value\n */\n function getHostName(url) {\n return (0, url_parse_1.default)(url).hostname;\n }\n URLExt.getHostName = getHostName;\n function normalize(url) {\n return url && parse(url).toString();\n }\n URLExt.normalize = normalize;\n /**\n * Join a sequence of url components and normalizes as in node `path.join`.\n *\n * @param parts - The url components.\n *\n * @returns the joined url.\n */\n function join(...parts) {\n let u = (0, url_parse_1.default)(parts[0], {});\n // Schema-less URL can be only parsed as relative to a base URL\n // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326\n const isSchemaLess = u.protocol === '' && u.slashes;\n if (isSchemaLess) {\n u = (0, url_parse_1.default)(parts[0], 'https:' + parts[0]);\n }\n const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${u.auth}${u.auth ? '@' : ''}${u.host}`;\n // If there was a prefix, then the first path must start at the root.\n const path = path_1.posix.join(`${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`, ...parts.slice(1));\n return `${prefix}${path === '.' ? '' : path}`;\n }\n URLExt.join = join;\n /**\n * Encode the components of a multi-segment url.\n *\n * @param url - The url to encode.\n *\n * @returns the encoded url.\n *\n * #### Notes\n * Preserves the `'/'` separators.\n * Should not include the base url, since all parts are escaped.\n */\n function encodeParts(url) {\n return join(...url.split('/').map(encodeURIComponent));\n }\n URLExt.encodeParts = encodeParts;\n /**\n * Return a serialized object string suitable for a query.\n *\n * @param object - The source object.\n *\n * @returns an encoded url query.\n *\n * #### Notes\n * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).\n */\n function objectToQueryString(value) {\n const keys = Object.keys(value).filter(key => key.length > 0);\n if (!keys.length) {\n return '';\n }\n return ('?' +\n keys\n .map(key => {\n const content = encodeURIComponent(String(value[key]));\n return key + (content ? '=' + content : '');\n })\n .join('&'));\n }\n URLExt.objectToQueryString = objectToQueryString;\n /**\n * Return a parsed object that represents the values in a query string.\n */\n function queryStringToObject(value) {\n return value\n .replace(/^\\?/, '')\n .split('&')\n .reduce((acc, val) => {\n const [key, value] = val.split('=');\n if (key.length > 0) {\n acc[key] = decodeURIComponent(value || '');\n }\n return acc;\n }, {});\n }\n URLExt.queryStringToObject = queryStringToObject;\n /**\n * Test whether the url is a local url.\n *\n * #### Notes\n * This function returns `false` for any fully qualified url, including\n * `data:`, `file:`, and `//` protocol URLs.\n */\n function isLocal(url) {\n const { protocol } = parse(url);\n return ((!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&\n url.indexOf('/') !== 0);\n }\n URLExt.isLocal = isLocal;\n})(URLExt = exports.URLExt || (exports.URLExt = {}));\n//# sourceMappingURL=url.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DataConnector = void 0;\n/**\n * An abstract class that adheres to the data connector interface.\n *\n * @typeparam T - The basic entity response type a service's connector.\n *\n * @typeparam U - The basic entity request type, which is conventionally the\n * same as the response type but may be different if a service's implementation\n * requires input data to be different from output responses. Defaults to `T`.\n *\n * @typeparam V - The basic token applied to a request, conventionally a string\n * ID or filter, but may be set to a different type when an implementation\n * requires it. Defaults to `string`.\n *\n * @typeparam W - The type of the optional `query` parameter of the `list`\n * method. Defaults to `string`.\n *\n * #### Notes\n * The only abstract method in this class is the `fetch` method, which must be\n * reimplemented by all subclasses. The `remove` and `save` methods have a\n * default implementation that returns a promise that will always reject. This\n * class is a convenience superclass for connectors that only need to `fetch`.\n */\nclass DataConnector {\n /**\n * Retrieve the list of items available from the data connector.\n *\n * @param query - The optional query filter to apply to the connector request.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can list.\n */\n async list(query) {\n throw new Error('DataConnector#list method has not been implemented.');\n }\n /**\n * Remove a value using the data connector.\n *\n * @param id - The identifier for the data being removed.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can remove.\n */\n async remove(id) {\n throw new Error('DataConnector#remove method has not been implemented.');\n }\n /**\n * Save a value using the data connector.\n *\n * @param id - The identifier for the data being saved.\n *\n * @param value - The data being saved.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can save.\n */\n async save(id, value) {\n throw new Error('DataConnector#save method has not been implemented.');\n }\n}\nexports.DataConnector = DataConnector;\n//# sourceMappingURL=dataconnector.js.map","\"use strict\";\n/* -----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module statedb\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./dataconnector\"), exports);\n__exportStar(require(\"./interfaces\"), exports);\n__exportStar(require(\"./restorablepool\"), exports);\n__exportStar(require(\"./statedb\"), exports);\n__exportStar(require(\"./tokens\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=interfaces.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RestorablePool = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst properties_1 = require(\"@lumino/properties\");\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * An object pool that supports restoration.\n *\n * @typeparam T - The type of object being tracked.\n */\nclass RestorablePool {\n /**\n * Create a new restorable pool.\n *\n * @param options - The instantiation options for a restorable pool.\n */\n constructor(options) {\n this._added = new signaling_1.Signal(this);\n this._current = null;\n this._currentChanged = new signaling_1.Signal(this);\n this._hasRestored = false;\n this._isDisposed = false;\n this._objects = new Set();\n this._restore = null;\n this._restored = new coreutils_1.PromiseDelegate();\n this._updated = new signaling_1.Signal(this);\n this.namespace = options.namespace;\n }\n /**\n * A signal emitted when an object object is added.\n *\n * #### Notes\n * This signal will only fire when an object is added to the pool.\n * It will not fire if an object injected into the pool.\n */\n get added() {\n return this._added;\n }\n /**\n * The current object.\n *\n * #### Notes\n * The restorable pool does not set `current`. It is intended for client use.\n *\n * If `current` is set to an object that does not exist in the pool, it is a\n * no-op.\n */\n get current() {\n return this._current;\n }\n set current(obj) {\n if (this._current === obj) {\n return;\n }\n if (obj !== null && this._objects.has(obj)) {\n this._current = obj;\n this._currentChanged.emit(this._current);\n }\n }\n /**\n * A signal emitted when the current widget changes.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * Test whether the pool is disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * A promise resolved when the restorable pool has been restored.\n */\n get restored() {\n return this._restored.promise;\n }\n /**\n * The number of objects held by the pool.\n */\n get size() {\n return this._objects.size;\n }\n /**\n * A signal emitted when an object is updated.\n */\n get updated() {\n return this._updated;\n }\n /**\n * Add a new object to the pool.\n *\n * @param obj - The object object being added.\n *\n * #### Notes\n * The object passed into the pool is added synchronously; its existence in\n * the pool can be checked with the `has()` method. The promise this method\n * returns resolves after the object has been added and saved to an underlying\n * restoration connector, if one is available.\n */\n async add(obj) {\n var _a, _b;\n if (obj.isDisposed) {\n const warning = 'A disposed object cannot be added.';\n console.warn(warning, obj);\n throw new Error(warning);\n }\n if (this._objects.has(obj)) {\n const warning = 'This object already exists in the pool.';\n console.warn(warning, obj);\n throw new Error(warning);\n }\n this._objects.add(obj);\n obj.disposed.connect(this._onInstanceDisposed, this);\n if (Private.injectedProperty.get(obj)) {\n return;\n }\n if (this._restore) {\n const { connector } = this._restore;\n const objName = this._restore.name(obj);\n if (objName) {\n const name = `${this.namespace}:${objName}`;\n const data = (_b = (_a = this._restore).args) === null || _b === void 0 ? void 0 : _b.call(_a, obj);\n Private.nameProperty.set(obj, name);\n await connector.save(name, { data });\n }\n }\n // Emit the added signal.\n this._added.emit(obj);\n }\n /**\n * Dispose of the resources held by the pool.\n *\n * #### Notes\n * Disposing a pool does not affect the underlying data in the data connector,\n * it simply disposes the client-side pool without making any connector calls.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._current = null;\n this._isDisposed = true;\n this._objects.clear();\n signaling_1.Signal.clearData(this);\n }\n /**\n * Find the first object in the pool that satisfies a filter function.\n *\n * @param - fn The filter function to call on each object.\n */\n find(fn) {\n const values = this._objects.values();\n for (const value of values) {\n if (fn(value)) {\n return value;\n }\n }\n return undefined;\n }\n /**\n * Iterate through each object in the pool.\n *\n * @param fn - The function to call on each object.\n */\n forEach(fn) {\n this._objects.forEach(fn);\n }\n /**\n * Filter the objects in the pool based on a predicate.\n *\n * @param fn - The function by which to filter.\n */\n filter(fn) {\n const filtered = [];\n this.forEach(obj => {\n if (fn(obj)) {\n filtered.push(obj);\n }\n });\n return filtered;\n }\n /**\n * Inject an object into the restorable pool without the pool handling its\n * restoration lifecycle.\n *\n * @param obj - The object to inject into the pool.\n */\n inject(obj) {\n Private.injectedProperty.set(obj, true);\n return this.add(obj);\n }\n /**\n * Check if this pool has the specified object.\n *\n * @param obj - The object whose existence is being checked.\n */\n has(obj) {\n return this._objects.has(obj);\n }\n /**\n * Restore the objects in this pool's namespace.\n *\n * @param options - The configuration options that describe restoration.\n *\n * @returns A promise that resolves when restoration has completed.\n *\n * #### Notes\n * This function should almost never be invoked by client code. Its primary\n * use case is to be invoked by a layout restorer plugin that handles\n * multiple restorable pools and, when ready, asks them each to restore their\n * respective objects.\n */\n async restore(options) {\n if (this._hasRestored) {\n throw new Error('This pool has already been restored.');\n }\n this._hasRestored = true;\n const { command, connector, registry, when } = options;\n const namespace = this.namespace;\n const promises = when\n ? [connector.list(namespace)].concat(when)\n : [connector.list(namespace)];\n this._restore = options;\n const [saved] = await Promise.all(promises);\n const values = await Promise.all(saved.ids.map(async (id, index) => {\n const value = saved.values[index];\n const args = value && value.data;\n if (args === undefined) {\n return connector.remove(id);\n }\n // Execute the command and if it fails, delete the state restore data.\n return registry\n .execute(command, args)\n .catch(() => connector.remove(id));\n }));\n this._restored.resolve();\n return values;\n }\n /**\n * Save the restore data for a given object.\n *\n * @param obj - The object being saved.\n */\n async save(obj) {\n var _a, _b;\n const injected = Private.injectedProperty.get(obj);\n if (!this._restore || !this.has(obj) || injected) {\n return;\n }\n const { connector } = this._restore;\n const objName = this._restore.name(obj);\n const oldName = Private.nameProperty.get(obj);\n const newName = objName ? `${this.namespace}:${objName}` : '';\n if (oldName && oldName !== newName) {\n await connector.remove(oldName);\n }\n // Set the name property irrespective of whether the new name is null.\n Private.nameProperty.set(obj, newName);\n if (newName) {\n const data = (_b = (_a = this._restore).args) === null || _b === void 0 ? void 0 : _b.call(_a, obj);\n await connector.save(newName, { data });\n }\n if (oldName !== newName) {\n this._updated.emit(obj);\n }\n }\n /**\n * Clean up after disposed objects.\n */\n _onInstanceDisposed(obj) {\n this._objects.delete(obj);\n if (obj === this._current) {\n this._current = null;\n this._currentChanged.emit(this._current);\n }\n if (Private.injectedProperty.get(obj)) {\n return;\n }\n if (!this._restore) {\n return;\n }\n const { connector } = this._restore;\n const name = Private.nameProperty.get(obj);\n if (name) {\n void connector.remove(name);\n }\n }\n}\nexports.RestorablePool = RestorablePool;\n/*\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * An attached property to indicate whether an object has been injected.\n */\n Private.injectedProperty = new properties_1.AttachedProperty({\n name: 'injected',\n create: () => false\n });\n /**\n * An attached property for an object's ID.\n */\n Private.nameProperty = new properties_1.AttachedProperty({\n name: 'name',\n create: () => ''\n });\n})(Private || (Private = {}));\n//# sourceMappingURL=restorablepool.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StateDB = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * The default concrete implementation of a state database.\n */\nclass StateDB {\n /**\n * Create a new state database.\n *\n * @param options - The instantiation options for a state database.\n */\n constructor(options = {}) {\n this._changed = new signaling_1.Signal(this);\n const { connector, transform } = options;\n this._connector = connector || new StateDB.Connector();\n if (!transform) {\n this._ready = Promise.resolve(undefined);\n }\n else {\n this._ready = transform.then(transformation => {\n const { contents, type } = transformation;\n switch (type) {\n case 'cancel':\n return;\n case 'clear':\n return this._clear();\n case 'merge':\n return this._merge(contents || {});\n case 'overwrite':\n return this._overwrite(contents || {});\n default:\n return;\n }\n });\n }\n }\n /**\n * A signal that emits the change type any time a value changes.\n */\n get changed() {\n return this._changed;\n }\n /**\n * Clear the entire database.\n */\n async clear() {\n await this._ready;\n await this._clear();\n }\n /**\n * Retrieve a saved bundle from the database.\n *\n * @param id - The identifier used to retrieve a data bundle.\n *\n * @returns A promise that bears a data payload if available.\n *\n * #### Notes\n * The `id` values of stored items in the state database are formatted:\n * `'namespace:identifier'`, which is the same convention that command\n * identifiers in JupyterLab use as well. While this is not a technical\n * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for\n * using the `list(namespace: string)` method.\n *\n * The promise returned by this method may be rejected if an error occurs in\n * retrieving the data. Non-existence of an `id` will succeed with the `value`\n * `undefined`.\n */\n async fetch(id) {\n await this._ready;\n return this._fetch(id);\n }\n /**\n * Retrieve all the saved bundles for a namespace.\n *\n * @param filter - The namespace prefix to retrieve.\n *\n * @returns A promise that bears a collection of payloads for a namespace.\n *\n * #### Notes\n * Namespaces are entirely conventional entities. The `id` values of stored\n * items in the state database are formatted: `'namespace:identifier'`, which\n * is the same convention that command identifiers in JupyterLab use as well.\n *\n * If there are any errors in retrieving the data, they will be logged to the\n * console in order to optimistically return any extant data without failing.\n * This promise will always succeed.\n */\n async list(namespace) {\n await this._ready;\n return this._list(namespace);\n }\n /**\n * Remove a value from the database.\n *\n * @param id - The identifier for the data being removed.\n *\n * @returns A promise that is rejected if remove fails and succeeds otherwise.\n */\n async remove(id) {\n await this._ready;\n await this._remove(id);\n this._changed.emit({ id, type: 'remove' });\n }\n /**\n * Save a value in the database.\n *\n * @param id - The identifier for the data being saved.\n *\n * @param value - The data being saved.\n *\n * @returns A promise that is rejected if saving fails and succeeds otherwise.\n *\n * #### Notes\n * The `id` values of stored items in the state database are formatted:\n * `'namespace:identifier'`, which is the same convention that command\n * identifiers in JupyterLab use as well. While this is not a technical\n * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for\n * using the `list(namespace: string)` method.\n */\n async save(id, value) {\n await this._ready;\n await this._save(id, value);\n this._changed.emit({ id, type: 'save' });\n }\n /**\n * Return a serialized copy of the state database's entire contents.\n *\n * @returns A promise that resolves with the database contents as JSON.\n */\n async toJSON() {\n await this._ready;\n const { ids, values } = await this._list();\n return values.reduce((acc, val, idx) => {\n acc[ids[idx]] = val;\n return acc;\n }, {});\n }\n /**\n * Clear the entire database.\n */\n async _clear() {\n await Promise.all((await this._list()).ids.map(id => this._remove(id)));\n }\n /**\n * Fetch a value from the database.\n */\n async _fetch(id) {\n const value = await this._connector.fetch(id);\n if (value) {\n return JSON.parse(value).v;\n }\n }\n /**\n * Fetch a list from the database.\n */\n async _list(namespace = '') {\n const { ids, values } = await this._connector.list(namespace);\n return {\n ids,\n values: values.map(val => JSON.parse(val).v)\n };\n }\n /**\n * Merge data into the state database.\n */\n async _merge(contents) {\n await Promise.all(Object.keys(contents).map(key => contents[key] && this._save(key, contents[key])));\n }\n /**\n * Overwrite the entire database with new contents.\n */\n async _overwrite(contents) {\n await this._clear();\n await this._merge(contents);\n }\n /**\n * Remove a key in the database.\n */\n async _remove(id) {\n return this._connector.remove(id);\n }\n /**\n * Save a key and its value in the database.\n */\n async _save(id, value) {\n return this._connector.save(id, JSON.stringify({ v: value }));\n }\n}\nexports.StateDB = StateDB;\n/**\n * A namespace for StateDB statics.\n */\n(function (StateDB) {\n /**\n * An in-memory string key/value data connector.\n */\n class Connector {\n constructor() {\n this._storage = {};\n }\n /**\n * Retrieve an item from the data connector.\n */\n async fetch(id) {\n return this._storage[id];\n }\n /**\n * Retrieve the list of items available from the data connector.\n *\n * @param namespace - If not empty, only keys whose first token before `:`\n * exactly match `namespace` will be returned, e.g. `foo` in `foo:bar`.\n */\n async list(namespace = '') {\n return Object.keys(this._storage).reduce((acc, val) => {\n if (namespace === '' ? true : namespace === val.split(':')[0]) {\n acc.ids.push(val);\n acc.values.push(this._storage[val]);\n }\n return acc;\n }, { ids: [], values: [] });\n }\n /**\n * Remove a value using the data connector.\n */\n async remove(id) {\n delete this._storage[id];\n }\n /**\n * Save a value using the data connector.\n */\n async save(id, value) {\n this._storage[id] = value;\n }\n }\n StateDB.Connector = Connector;\n})(StateDB = exports.StateDB || (exports.StateDB = {}));\n//# sourceMappingURL=statedb.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IStateDB = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * The default state database token.\n */\nexports.IStateDB = new coreutils_1.Token('@jupyterlab/coreutils:IStateDB', `A service for the JupyterLab state database.\n Use this if you want to store data that will persist across page loads.\n See \"state database\" for more information.`);\n//# sourceMappingURL=tokens.js.map","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","import { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\n/**\n * A disposable object which delegates to a callback function.\n */\nclass DisposableDelegate {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn) {\n this._fn = fn;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return !this._fn;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n}\n/**\n * An observable disposable object which delegates to a callback function.\n */\nclass ObservableDisposableDelegate extends DisposableDelegate {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * An object which manages a collection of disposable items.\n */\nclass DisposableSet {\n constructor() {\n this._isDisposed = false;\n this._items = new Set();\n }\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item) {\n return this._items.has(item);\n }\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item) {\n this._items.add(item);\n }\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item) {\n this._items.delete(item);\n }\n /**\n * Remove all items from the set.\n */\n clear() {\n this._items.clear();\n }\n}\n/**\n * The namespace for the `DisposableSet` class statics.\n */\n(function (DisposableSet) {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n DisposableSet.from = from;\n})(DisposableSet || (DisposableSet = {}));\n/**\n * An observable object which manages a collection of disposable items.\n */\nclass ObservableDisposableSet extends DisposableSet {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\n(function (ObservableDisposableSet) {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n ObservableDisposableSet.from = from;\n})(ObservableDisposableSet || (ObservableDisposableSet = {}));\n\nexport { DisposableDelegate, DisposableSet, ObservableDisposableDelegate, ObservableDisposableSet };\n//# sourceMappingURL=index.es6.js.map\n","import { PromiseDelegate, JSONExt } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A class that wraps an asynchronous function to poll at a regular interval\n * with exponential increases to the interval length if the poll fails.\n *\n * @typeparam T - The resolved type of the factory's promises.\n * Defaults to `any`.\n *\n * @typeparam U - The rejected type of the factory's promises.\n * Defaults to `any`.\n *\n * @typeparam V - An optional type to extend the phases supported by a poll.\n * Defaults to `standby`, which already exists in the `Phase` type.\n */\nclass Poll {\n /**\n * Instantiate a new poll with exponential backoff in case of failure.\n *\n * @param options - The poll instantiation options.\n */\n constructor(options) {\n var _a;\n this._disposed = new Signal(this);\n this._lingered = 0;\n this._tick = new PromiseDelegate();\n this._ticked = new Signal(this);\n this._factory = options.factory;\n this._linger = (_a = options.linger) !== null && _a !== void 0 ? _a : Private.DEFAULT_LINGER;\n this._standby = options.standby || Private.DEFAULT_STANDBY;\n this._state = { ...Private.DEFAULT_STATE, timestamp: new Date().getTime() };\n // Normalize poll frequency `max` to be the greater of\n // default `max`, `options.frequency.max`, or `options.frequency.interval`.\n const frequency = options.frequency || {};\n const max = Math.max(frequency.interval || 0, frequency.max || 0, Private.DEFAULT_FREQUENCY.max);\n this.frequency = { ...Private.DEFAULT_FREQUENCY, ...frequency, ...{ max } };\n this.name = options.name || Private.DEFAULT_NAME;\n if ('auto' in options ? options.auto : true) {\n setTimeout(() => this.start());\n }\n }\n /**\n * A signal emitted when the poll is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * The polling frequency parameters.\n */\n get frequency() {\n return this._frequency;\n }\n set frequency(frequency) {\n if (this.isDisposed || JSONExt.deepEqual(frequency, this.frequency || {})) {\n return;\n }\n let { backoff, interval, max } = frequency;\n interval = Math.round(interval);\n max = Math.round(max);\n if (typeof backoff === 'number' && backoff < 1) {\n throw new Error('Poll backoff growth factor must be at least 1');\n }\n if ((interval < 0 || interval > max) && interval !== Poll.NEVER) {\n throw new Error('Poll interval must be between 0 and max');\n }\n if (max > Poll.MAX_INTERVAL && max !== Poll.NEVER) {\n throw new Error(`Max interval must be less than ${Poll.MAX_INTERVAL}`);\n }\n this._frequency = { backoff, interval, max };\n }\n /**\n * Whether the poll is disposed.\n */\n get isDisposed() {\n return this.state.phase === 'disposed';\n }\n /**\n * Indicates when the poll switches to standby.\n */\n get standby() {\n return this._standby;\n }\n set standby(standby) {\n if (this.isDisposed || this.standby === standby) {\n return;\n }\n this._standby = standby;\n }\n /**\n * The poll state, which is the content of the current poll tick.\n */\n get state() {\n return this._state;\n }\n /**\n * A promise that resolves when the poll next ticks.\n */\n get tick() {\n return this._tick.promise;\n }\n /**\n * A signal emitted when the poll ticks and fires off a new request.\n */\n get ticked() {\n return this._ticked;\n }\n /**\n * Return an async iterator that yields every tick.\n */\n async *[Symbol.asyncIterator]() {\n while (!this.isDisposed) {\n yield this.state;\n await this.tick.catch(() => undefined);\n }\n }\n /**\n * Dispose the poll.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._state = {\n ...Private.DISPOSED_STATE,\n timestamp: new Date().getTime()\n };\n this._tick.promise.catch(_ => undefined);\n this._tick.reject(new Error(`Poll (${this.name}) is disposed.`));\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n /**\n * Refreshes the poll. Schedules `refreshed` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n *\n * #### Notes\n * The returned promise resolves after the tick is scheduled, but before\n * the polling action is run. To wait until after the poll action executes,\n * await the `poll.tick` promise: `await poll.refresh(); await poll.tick;`\n */\n refresh() {\n return this.schedule({\n cancel: ({ phase }) => phase === 'refreshed',\n interval: Poll.IMMEDIATE,\n phase: 'refreshed'\n });\n }\n /**\n * Schedule the next poll tick.\n *\n * @param next - The next poll state data to schedule. Defaults to standby.\n *\n * @param next.cancel - Cancels state transition if function returns `true`.\n *\n * @returns A promise that resolves when the next poll state is active.\n *\n * #### Notes\n * This method is not meant to be invoked by user code typically. It is public\n * to allow poll instances to be composed into classes that schedule ticks.\n */\n async schedule(next = {}) {\n if (this.isDisposed) {\n return;\n }\n // Check if the phase transition should be canceled.\n if (next.cancel && next.cancel(this.state)) {\n return;\n }\n // Update poll state.\n const pending = this._tick;\n const scheduled = new PromiseDelegate();\n const state = {\n interval: this.frequency.interval,\n payload: null,\n phase: 'standby',\n timestamp: new Date().getTime(),\n ...next\n };\n this._state = state;\n this._tick = scheduled;\n // Clear the schedule if possible.\n clearTimeout(this._timeout);\n // Emit ticked signal, resolve pending promise, and await its settlement.\n this._ticked.emit(this.state);\n pending.resolve(this);\n await pending.promise;\n if (state.interval === Poll.NEVER) {\n this._timeout = undefined;\n return;\n }\n // Schedule next execution and cache its timeout handle.\n const execute = () => {\n if (this.isDisposed || this.tick !== scheduled.promise) {\n return;\n }\n this._execute();\n };\n // Cache the handle in case it needs to be unscheduled.\n this._timeout = setTimeout(execute, state.interval);\n }\n /**\n * Starts the poll. Schedules `started` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n */\n start() {\n return this.schedule({\n cancel: ({ phase }) => phase !== 'constructed' && phase !== 'standby' && phase !== 'stopped',\n interval: Poll.IMMEDIATE,\n phase: 'started'\n });\n }\n /**\n * Stops the poll. Schedules `stopped` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n */\n stop() {\n return this.schedule({\n cancel: ({ phase }) => phase === 'stopped',\n interval: Poll.NEVER,\n phase: 'stopped'\n });\n }\n /**\n * Whether the poll is hidden.\n *\n * #### Notes\n * This property is only relevant in a browser context.\n */\n get hidden() {\n return Private.hidden;\n }\n /**\n * Execute a new poll factory promise or stand by if necessary.\n */\n _execute() {\n let standby = typeof this.standby === 'function' ? this.standby() : this.standby;\n // Check if execution should proceed, linger, or stand by.\n if (standby === 'never') {\n standby = false;\n }\n else if (standby === 'when-hidden') {\n if (this.hidden) {\n standby = ++this._lingered > this._linger;\n }\n else {\n this._lingered = 0;\n standby = false;\n }\n }\n // If in standby mode schedule next tick without calling the factory.\n if (standby) {\n void this.schedule();\n return;\n }\n const pending = this.tick;\n this._factory(this.state)\n .then((resolved) => {\n if (this.isDisposed || this.tick !== pending) {\n return;\n }\n void this.schedule({\n payload: resolved,\n phase: this.state.phase === 'rejected' ? 'reconnected' : 'resolved'\n });\n })\n .catch((rejected) => {\n if (this.isDisposed || this.tick !== pending) {\n return;\n }\n void this.schedule({\n interval: Private.sleep(this.frequency, this.state),\n payload: rejected,\n phase: 'rejected'\n });\n });\n }\n}\n/**\n * A namespace for `Poll` types, interfaces, and statics.\n */\n(function (Poll) {\n /**\n * An interval value in ms that indicates the poll should tick immediately.\n */\n Poll.IMMEDIATE = 0;\n /**\n * Delays are 32-bit integers in many browsers so intervals need to be capped.\n *\n * #### Notes\n * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value\n */\n Poll.MAX_INTERVAL = 2147483647;\n /**\n * An interval value that indicates the poll should never tick.\n */\n Poll.NEVER = Infinity;\n})(Poll || (Poll = {}));\n/**\n * A namespace for private module data.\n */\nvar Private;\n(function (Private) {\n /**\n * The default backoff growth rate if `backoff` is `true`.\n */\n Private.DEFAULT_BACKOFF = 3;\n /**\n * The default polling frequency.\n */\n Private.DEFAULT_FREQUENCY = {\n backoff: true,\n interval: 1000,\n max: 30 * 1000\n };\n /**\n * The default number of times to `linger` when a poll is hidden.\n */\n Private.DEFAULT_LINGER = 1;\n /**\n * The default poll name.\n */\n Private.DEFAULT_NAME = 'unknown';\n /**\n * The default poll standby behavior.\n */\n Private.DEFAULT_STANDBY = 'when-hidden';\n /**\n * The first poll tick state's default values superseded in constructor.\n */\n Private.DEFAULT_STATE = {\n interval: Poll.NEVER,\n payload: null,\n phase: 'constructed',\n timestamp: new Date(0).getTime()\n };\n /**\n * The disposed tick state values.\n */\n Private.DISPOSED_STATE = {\n interval: Poll.NEVER,\n payload: null,\n phase: 'disposed',\n timestamp: new Date(0).getTime()\n };\n /**\n * Returns the number of milliseconds to sleep before the next tick.\n *\n * @param frequency - The poll's base frequency.\n * @param last - The poll's last tick.\n */\n function sleep(frequency, last) {\n const { backoff, interval, max } = frequency;\n if (interval === Poll.NEVER) {\n return interval;\n }\n const growth = backoff === true ? Private.DEFAULT_BACKOFF : backoff === false ? 1 : backoff;\n const random = getRandomIntInclusive(interval, last.interval * growth);\n return Math.min(max, random);\n }\n Private.sleep = sleep;\n /**\n * Keep track of whether the document is hidden. This flag is only relevant in\n * a browser context.\n *\n * Listen to `visibilitychange` event to set the `hidden` flag.\n *\n * Listening to `pagehide` is also necessary because Safari support for\n * `visibilitychange` events is partial, cf.\n * https://developer.mozilla.org/docs/Web/API/Document/visibilitychange_event\n */\n Private.hidden = (() => {\n if (typeof document === 'undefined') {\n return false;\n }\n document.addEventListener('visibilitychange', () => {\n Private.hidden = document.visibilityState === 'hidden';\n });\n document.addEventListener('pagehide', () => {\n Private.hidden = document.visibilityState === 'hidden';\n });\n return document.visibilityState === 'hidden';\n })();\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A base class to implement rate limiters with different invocation strategies.\n *\n * @typeparam T - The resolved type of the underlying function.\n *\n * @typeparam U - The rejected type of the underlying function.\n *\n * @typeparam V - Arguments for the underlying function.\n */\nclass RateLimiter {\n /**\n * Instantiate a rate limiter.\n *\n * @param fn - The function to rate limit.\n *\n * @param limit - The rate limit; defaults to 500ms.\n */\n constructor(fn, limit = 500) {\n /**\n * Arguments for the underlying function.\n */\n this.args = undefined;\n /**\n * A promise that resolves on each successful invocation.\n */\n this.payload = null;\n this.limit = limit;\n this.poll = new Poll({\n auto: false,\n factory: async () => {\n const { args } = this;\n this.args = undefined;\n return fn(...args);\n },\n frequency: { backoff: false, interval: Poll.NEVER, max: Poll.NEVER },\n standby: 'never'\n });\n this.payload = new PromiseDelegate();\n this.poll.ticked.connect((_, state) => {\n const { payload } = this;\n if (state.phase === 'resolved') {\n this.payload = new PromiseDelegate();\n payload.resolve(state.payload);\n return;\n }\n if (state.phase === 'rejected' || state.phase === 'stopped') {\n this.payload = new PromiseDelegate();\n payload.promise.catch(_ => undefined);\n payload.reject(state.payload);\n return;\n }\n }, this);\n }\n /**\n * Whether the rate limiter is disposed.\n */\n get isDisposed() {\n return this.payload === null;\n }\n /**\n * Disposes the rate limiter.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this.args = undefined;\n this.payload = null;\n this.poll.dispose();\n }\n /**\n * Stop the function if it is mid-flight.\n */\n async stop() {\n return this.poll.stop();\n }\n}\n/**\n * Wraps and debounces a function that can be called multiple times and only\n * executes the underlying function one `interval` after the last invocation.\n *\n * @typeparam T - The resolved type of the underlying function. Defaults to any.\n *\n * @typeparam U - The rejected type of the underlying function. Defaults to any.\n *\n * @typeparam V - Arguments for the underlying function. Defaults to any[].\n */\nclass Debouncer extends RateLimiter {\n /**\n * Invokes the function and only executes after rate limit has elapsed.\n * Each invocation resets the timer.\n */\n invoke(...args) {\n this.args = args;\n void this.poll.schedule({ interval: this.limit, phase: 'invoked' });\n return this.payload.promise;\n }\n}\n/**\n * Wraps and throttles a function that can be called multiple times and only\n * executes the underlying function once per `interval`.\n *\n * @typeparam T - The resolved type of the underlying function. Defaults to any.\n *\n * @typeparam U - The rejected type of the underlying function. Defaults to any.\n *\n * @typeparam V - Arguments for the underlying function. Defaults to any[].\n */\nclass Throttler extends RateLimiter {\n /**\n * Instantiate a throttler.\n *\n * @param fn - The function being throttled.\n *\n * @param options - Throttling configuration or throttling limit in ms.\n *\n * #### Notes\n * The `edge` defaults to `leading`; the `limit` defaults to `500`.\n */\n constructor(fn, options) {\n super(fn, typeof options === 'number' ? options : options && options.limit);\n this._trailing = false;\n if (typeof options !== 'number' && options && options.edge === 'trailing') {\n this._trailing = true;\n }\n this._interval = this._trailing ? this.limit : Poll.IMMEDIATE;\n }\n /**\n * Throttles function invocations if one is currently in flight.\n */\n invoke(...args) {\n const idle = this.poll.state.phase !== 'invoked';\n if (idle || this._trailing) {\n this.args = args;\n }\n if (idle) {\n void this.poll.schedule({ interval: this._interval, phase: 'invoked' });\n }\n return this.payload.promise;\n }\n}\n\nexport { Debouncer, Poll, RateLimiter, Throttler };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module properties\n */\n/**\n * A class which attaches a value to an external object.\n *\n * #### Notes\n * Attached properties are used to extend the state of an object with\n * semantic data from an unrelated class. They also encapsulate value\n * creation, coercion, and notification.\n *\n * Because attached property values are stored in a hash table, which\n * in turn is stored in a WeakMap keyed on the owner object, there is\n * non-trivial storage overhead involved in their use. The pattern is\n * therefore best used for the storage of rare data.\n */\nclass AttachedProperty {\n /**\n * Construct a new attached property.\n *\n * @param options - The options for initializing the property.\n */\n constructor(options) {\n this._pid = Private.nextPID();\n this.name = options.name;\n this._create = options.create;\n this._coerce = options.coerce || null;\n this._compare = options.compare || null;\n this._changed = options.changed || null;\n }\n /**\n * Get the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @returns The current value of the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and assigned as the current value of the property.\n */\n get(owner) {\n let value;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n value = map[this._pid];\n }\n else {\n value = map[this._pid] = this._createValue(owner);\n }\n return value;\n }\n /**\n * Set the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @param value - The value for the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n set(owner, value) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, value);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Explicitly coerce the current property value for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n coerce(owner) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, oldValue);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Get or create the default value for the given owner.\n */\n _createValue(owner) {\n let create = this._create;\n return create(owner);\n }\n /**\n * Coerce the value for the given owner.\n */\n _coerceValue(owner, value) {\n let coerce = this._coerce;\n return coerce ? coerce(owner, value) : value;\n }\n /**\n * Compare the old value and new value for equality.\n */\n _compareValue(oldValue, newValue) {\n let compare = this._compare;\n return compare ? compare(oldValue, newValue) : oldValue === newValue;\n }\n /**\n * Run the change notification if the given values are different.\n */\n _maybeNotify(owner, oldValue, newValue) {\n let changed = this._changed;\n if (changed && !this._compareValue(oldValue, newValue)) {\n changed(owner, oldValue, newValue);\n }\n }\n}\n/**\n * The namespace for the `AttachedProperty` class statics.\n */\n(function (AttachedProperty) {\n /**\n * Clear the stored property data for the given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * This will clear all property values for the owner, but it will\n * **not** run the change notification for any of the properties.\n */\n function clearData(owner) {\n Private.ownerData.delete(owner);\n }\n AttachedProperty.clearData = clearData;\n})(AttachedProperty || (AttachedProperty = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A weak mapping of property owner to property map.\n */\n Private.ownerData = new WeakMap();\n /**\n * A function which computes successive unique property ids.\n */\n Private.nextPID = (() => {\n let id = 0;\n return () => {\n let rand = Math.random();\n let stem = `${rand}`.slice(2);\n return `pid-${stem}-${id++}`;\n };\n })();\n /**\n * Lookup the data map for the property owner.\n *\n * This will create the map if one does not already exist.\n */\n function ensureMap(owner) {\n let map = Private.ownerData.get(owner);\n if (map) {\n return map;\n }\n map = Object.create(null);\n Private.ownerData.set(owner, map);\n return map;\n }\n Private.ensureMap = ensureMap;\n})(Private || (Private = {}));\n\nexport { AttachedProperty };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nfunction* chain(...objects) {\n for (const object of objects) {\n yield* object;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nfunction* empty() {\n return;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nfunction* enumerate(object, start = 0) {\n for (const value of object) {\n yield [start++, value];\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* filter(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nfunction find(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nfunction findIndex(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nfunction min(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nfunction max(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nfunction minmax(object, fn) {\n let empty = true;\n let vmin;\n let vmax;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n }\n else if (fn(value, vmin) < 0) {\n vmin = value;\n }\n else if (fn(value, vmax) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin, vmax];\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nfunction toArray(object) {\n return Array.from(object);\n}\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nfunction toObject(object) {\n const result = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nfunction each(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nfunction every(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nfunction some(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* map(object, fn) {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nfunction* range(start, stop, step) {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n }\n else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nfunction reduce(object, fn, initial) {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n // Setup the initial accumlated value.\n let accumulator;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n }\n else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n // Iterate the rest of the values, updating the accumulator.\n let next;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n // Return the final accumulated value.\n return accumulator;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nfunction* repeat(value, count) {\n while (0 < count--) {\n yield value;\n }\n}\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nfunction* once(value) {\n yield value;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nfunction* retro(object) {\n if (typeof object.retro === 'function') {\n yield* object.retro();\n }\n else {\n for (let index = object.length - 1; index > -1; index--) {\n yield object[index];\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nfunction* stride(object, step) {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nfunction* take(object, count) {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nfunction* zip(...objects) {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n\nexport { ArrayExt, StringExt, chain, each, empty, enumerate, every, filter, find, findIndex, map, max, min, minmax, once, range, reduce, repeat, retro, some, stride, take, toArray, toObject, topologicSort, zip };\n//# sourceMappingURL=index.es6.js.map\n","import { find, ArrayExt } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nclass Signal {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender) {\n this.sender = sender;\n }\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot, thisArg) {\n return Private.connect(this, slot, thisArg);\n }\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot, thisArg) {\n return Private.disconnect(this, slot, thisArg);\n }\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args) {\n Private.emit(this, args);\n }\n}\n/**\n * The namespace for the `Signal` class statics.\n */\n(function (Signal) {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectBetween(sender, receiver) {\n Private.disconnectBetween(sender, receiver);\n }\n Signal.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n Private.disconnectSender(sender);\n }\n Signal.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectReceiver(receiver) {\n Private.disconnectReceiver(receiver);\n }\n Signal.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectAll(object) {\n Private.disconnectAll(object);\n }\n Signal.disconnectAll = disconnectAll;\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n function clearData(object) {\n Private.disconnectAll(object);\n }\n Signal.clearData = clearData;\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return Private.exceptionHandler;\n }\n Signal.getExceptionHandler = getExceptionHandler;\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n Signal.setExceptionHandler = setExceptionHandler;\n})(Signal || (Signal = {}));\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nclass Stream extends Signal {\n constructor() {\n super(...arguments);\n this._pending = new PromiseDelegate();\n }\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator]() {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n }\n catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args) {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n /**\n * Stop the stream's async iteration.\n */\n stop() {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The signal exception handler function.\n */\n Private.exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n function connect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n // Indicate a successful connection.\n return true;\n }\n Private.connect = connect;\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n function disconnect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver);\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n // Indicate a successful disconnection.\n return true;\n }\n Private.disconnect = disconnect;\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectBetween(sender, receiver) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n Private.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver));\n }\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n Private.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectReceiver(receiver) {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender));\n }\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n Private.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n function disconnectAll(object) {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n Private.disconnectAll = disconnectAll;\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n function emit(signal, args) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n Private.emit = emit;\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap();\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap();\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(connections, signal, slot, thisArg) {\n return find(connections, connection => connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg);\n }\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection, args) {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal.sender, args);\n }\n catch (err) {\n Private.exceptionHandler(err);\n }\n }\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection) {\n return connection.signal === null;\n }\n})(Private || (Private = {}));\n\nexport { Signal, Stream };\n//# sourceMappingURL=index.es6.js.map\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.JSON5 = factory());\n}(this, (function () { 'use strict';\n\n\tfunction createCommonjsModule(fn, module) {\n\t\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n\t}\n\n\tvar _global = createCommonjsModule(function (module) {\n\t// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\n\tvar global = module.exports = typeof window != 'undefined' && window.Math == Math\n\t ? window : typeof self != 'undefined' && self.Math == Math ? self\n\t // eslint-disable-next-line no-new-func\n\t : Function('return this')();\n\tif (typeof __g == 'number') { __g = global; } // eslint-disable-line no-undef\n\t});\n\n\tvar _core = createCommonjsModule(function (module) {\n\tvar core = module.exports = { version: '2.6.5' };\n\tif (typeof __e == 'number') { __e = core; } // eslint-disable-line no-undef\n\t});\n\tvar _core_1 = _core.version;\n\n\tvar _isObject = function (it) {\n\t return typeof it === 'object' ? it !== null : typeof it === 'function';\n\t};\n\n\tvar _anObject = function (it) {\n\t if (!_isObject(it)) { throw TypeError(it + ' is not an object!'); }\n\t return it;\n\t};\n\n\tvar _fails = function (exec) {\n\t try {\n\t return !!exec();\n\t } catch (e) {\n\t return true;\n\t }\n\t};\n\n\t// Thank's IE8 for his funny defineProperty\n\tvar _descriptors = !_fails(function () {\n\t return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;\n\t});\n\n\tvar document = _global.document;\n\t// typeof document.createElement is 'object' in old IE\n\tvar is = _isObject(document) && _isObject(document.createElement);\n\tvar _domCreate = function (it) {\n\t return is ? document.createElement(it) : {};\n\t};\n\n\tvar _ie8DomDefine = !_descriptors && !_fails(function () {\n\t return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7;\n\t});\n\n\t// 7.1.1 ToPrimitive(input [, PreferredType])\n\n\t// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n\t// and the second argument - flag - preferred type is a string\n\tvar _toPrimitive = function (it, S) {\n\t if (!_isObject(it)) { return it; }\n\t var fn, val;\n\t if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; }\n\t if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) { return val; }\n\t if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; }\n\t throw TypeError(\"Can't convert object to primitive value\");\n\t};\n\n\tvar dP = Object.defineProperty;\n\n\tvar f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) {\n\t _anObject(O);\n\t P = _toPrimitive(P, true);\n\t _anObject(Attributes);\n\t if (_ie8DomDefine) { try {\n\t return dP(O, P, Attributes);\n\t } catch (e) { /* empty */ } }\n\t if ('get' in Attributes || 'set' in Attributes) { throw TypeError('Accessors not supported!'); }\n\t if ('value' in Attributes) { O[P] = Attributes.value; }\n\t return O;\n\t};\n\n\tvar _objectDp = {\n\t\tf: f\n\t};\n\n\tvar _propertyDesc = function (bitmap, value) {\n\t return {\n\t enumerable: !(bitmap & 1),\n\t configurable: !(bitmap & 2),\n\t writable: !(bitmap & 4),\n\t value: value\n\t };\n\t};\n\n\tvar _hide = _descriptors ? function (object, key, value) {\n\t return _objectDp.f(object, key, _propertyDesc(1, value));\n\t} : function (object, key, value) {\n\t object[key] = value;\n\t return object;\n\t};\n\n\tvar hasOwnProperty = {}.hasOwnProperty;\n\tvar _has = function (it, key) {\n\t return hasOwnProperty.call(it, key);\n\t};\n\n\tvar id = 0;\n\tvar px = Math.random();\n\tvar _uid = function (key) {\n\t return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));\n\t};\n\n\tvar _library = false;\n\n\tvar _shared = createCommonjsModule(function (module) {\n\tvar SHARED = '__core-js_shared__';\n\tvar store = _global[SHARED] || (_global[SHARED] = {});\n\n\t(module.exports = function (key, value) {\n\t return store[key] || (store[key] = value !== undefined ? value : {});\n\t})('versions', []).push({\n\t version: _core.version,\n\t mode: _library ? 'pure' : 'global',\n\t copyright: '© 2019 Denis Pushkarev (zloirock.ru)'\n\t});\n\t});\n\n\tvar _functionToString = _shared('native-function-to-string', Function.toString);\n\n\tvar _redefine = createCommonjsModule(function (module) {\n\tvar SRC = _uid('src');\n\n\tvar TO_STRING = 'toString';\n\tvar TPL = ('' + _functionToString).split(TO_STRING);\n\n\t_core.inspectSource = function (it) {\n\t return _functionToString.call(it);\n\t};\n\n\t(module.exports = function (O, key, val, safe) {\n\t var isFunction = typeof val == 'function';\n\t if (isFunction) { _has(val, 'name') || _hide(val, 'name', key); }\n\t if (O[key] === val) { return; }\n\t if (isFunction) { _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); }\n\t if (O === _global) {\n\t O[key] = val;\n\t } else if (!safe) {\n\t delete O[key];\n\t _hide(O, key, val);\n\t } else if (O[key]) {\n\t O[key] = val;\n\t } else {\n\t _hide(O, key, val);\n\t }\n\t// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n\t})(Function.prototype, TO_STRING, function toString() {\n\t return typeof this == 'function' && this[SRC] || _functionToString.call(this);\n\t});\n\t});\n\n\tvar _aFunction = function (it) {\n\t if (typeof it != 'function') { throw TypeError(it + ' is not a function!'); }\n\t return it;\n\t};\n\n\t// optional / simple context binding\n\n\tvar _ctx = function (fn, that, length) {\n\t _aFunction(fn);\n\t if (that === undefined) { return fn; }\n\t switch (length) {\n\t case 1: return function (a) {\n\t return fn.call(that, a);\n\t };\n\t case 2: return function (a, b) {\n\t return fn.call(that, a, b);\n\t };\n\t case 3: return function (a, b, c) {\n\t return fn.call(that, a, b, c);\n\t };\n\t }\n\t return function (/* ...args */) {\n\t return fn.apply(that, arguments);\n\t };\n\t};\n\n\tvar PROTOTYPE = 'prototype';\n\n\tvar $export = function (type, name, source) {\n\t var IS_FORCED = type & $export.F;\n\t var IS_GLOBAL = type & $export.G;\n\t var IS_STATIC = type & $export.S;\n\t var IS_PROTO = type & $export.P;\n\t var IS_BIND = type & $export.B;\n\t var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE];\n\t var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {});\n\t var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {});\n\t var key, own, out, exp;\n\t if (IS_GLOBAL) { source = name; }\n\t for (key in source) {\n\t // contains in native\n\t own = !IS_FORCED && target && target[key] !== undefined;\n\t // export native or passed\n\t out = (own ? target : source)[key];\n\t // bind timers to global for call from export context\n\t exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out;\n\t // extend global\n\t if (target) { _redefine(target, key, out, type & $export.U); }\n\t // export\n\t if (exports[key] != out) { _hide(exports, key, exp); }\n\t if (IS_PROTO && expProto[key] != out) { expProto[key] = out; }\n\t }\n\t};\n\t_global.core = _core;\n\t// type bitmap\n\t$export.F = 1; // forced\n\t$export.G = 2; // global\n\t$export.S = 4; // static\n\t$export.P = 8; // proto\n\t$export.B = 16; // bind\n\t$export.W = 32; // wrap\n\t$export.U = 64; // safe\n\t$export.R = 128; // real proto method for `library`\n\tvar _export = $export;\n\n\t// 7.1.4 ToInteger\n\tvar ceil = Math.ceil;\n\tvar floor = Math.floor;\n\tvar _toInteger = function (it) {\n\t return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);\n\t};\n\n\t// 7.2.1 RequireObjectCoercible(argument)\n\tvar _defined = function (it) {\n\t if (it == undefined) { throw TypeError(\"Can't call method on \" + it); }\n\t return it;\n\t};\n\n\t// true -> String#at\n\t// false -> String#codePointAt\n\tvar _stringAt = function (TO_STRING) {\n\t return function (that, pos) {\n\t var s = String(_defined(that));\n\t var i = _toInteger(pos);\n\t var l = s.length;\n\t var a, b;\n\t if (i < 0 || i >= l) { return TO_STRING ? '' : undefined; }\n\t a = s.charCodeAt(i);\n\t return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff\n\t ? TO_STRING ? s.charAt(i) : a\n\t : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;\n\t };\n\t};\n\n\tvar $at = _stringAt(false);\n\t_export(_export.P, 'String', {\n\t // 21.1.3.3 String.prototype.codePointAt(pos)\n\t codePointAt: function codePointAt(pos) {\n\t return $at(this, pos);\n\t }\n\t});\n\n\tvar codePointAt = _core.String.codePointAt;\n\n\tvar max = Math.max;\n\tvar min = Math.min;\n\tvar _toAbsoluteIndex = function (index, length) {\n\t index = _toInteger(index);\n\t return index < 0 ? max(index + length, 0) : min(index, length);\n\t};\n\n\tvar fromCharCode = String.fromCharCode;\n\tvar $fromCodePoint = String.fromCodePoint;\n\n\t// length should be 1, old FF problem\n\t_export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {\n\t // 21.1.2.2 String.fromCodePoint(...codePoints)\n\t fromCodePoint: function fromCodePoint(x) {\n\t var arguments$1 = arguments;\n\t // eslint-disable-line no-unused-vars\n\t var res = [];\n\t var aLen = arguments.length;\n\t var i = 0;\n\t var code;\n\t while (aLen > i) {\n\t code = +arguments$1[i++];\n\t if (_toAbsoluteIndex(code, 0x10ffff) !== code) { throw RangeError(code + ' is not a valid code point'); }\n\t res.push(code < 0x10000\n\t ? fromCharCode(code)\n\t : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)\n\t );\n\t } return res.join('');\n\t }\n\t});\n\n\tvar fromCodePoint = _core.String.fromCodePoint;\n\n\t// This is a generated file. Do not edit.\n\tvar Space_Separator = /[\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/;\n\tvar ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A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\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\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0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09FC\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0AF9-\\u0AFF\\u0B01-\\u0B03\\u0B05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3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uF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DE11\\uDE13-\\uDE37\\uDE3E\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF00-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3C-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF50\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC00-\\uDC4A\\uDC50-\\uDC59\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-\\uDDC0\\uDDD8-\\uDDDD\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB7\\uDEC0-\\uDEC9\\uDF00-\\uDF19\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDCA0-\\uDCE9\\uDCFF\\uDE00-\\uDE3E\\uDE47\\uDE50-\\uDE83\\uDE86-\\uDE99\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\u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DCD0-\\uDCD6\\uDD00-\\uDD4A\\uDD50-\\uDD59]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/;\n\n\tvar unicode = {\n\t\tSpace_Separator: Space_Separator,\n\t\tID_Start: ID_Start,\n\t\tID_Continue: ID_Continue\n\t};\n\n\tvar util = {\n\t isSpaceSeparator: function isSpaceSeparator (c) {\n\t return typeof c === 'string' && unicode.Space_Separator.test(c)\n\t },\n\n\t isIdStartChar: function isIdStartChar (c) {\n\t return typeof c === 'string' && (\n\t (c >= 'a' && c <= 'z') ||\n\t (c >= 'A' && c <= 'Z') ||\n\t (c === '$') || (c === '_') ||\n\t unicode.ID_Start.test(c)\n\t )\n\t },\n\n\t isIdContinueChar: function isIdContinueChar (c) {\n\t return typeof c === 'string' && (\n\t (c >= 'a' && c <= 'z') ||\n\t (c >= 'A' && c <= 'Z') ||\n\t (c >= '0' && c <= '9') ||\n\t (c === '$') || (c === '_') ||\n\t (c === '\\u200C') || (c === '\\u200D') ||\n\t unicode.ID_Continue.test(c)\n\t )\n\t },\n\n\t isDigit: function isDigit (c) {\n\t return typeof c === 'string' && /[0-9]/.test(c)\n\t },\n\n\t isHexDigit: function isHexDigit (c) {\n\t return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)\n\t },\n\t};\n\n\tvar source;\n\tvar parseState;\n\tvar stack;\n\tvar pos;\n\tvar line;\n\tvar column;\n\tvar token;\n\tvar key;\n\tvar root;\n\n\tvar parse = function parse (text, reviver) {\n\t source = String(text);\n\t parseState = 'start';\n\t stack = [];\n\t pos = 0;\n\t line = 1;\n\t column = 0;\n\t token = undefined;\n\t key = undefined;\n\t root = undefined;\n\n\t do {\n\t token = lex();\n\n\t // This code is unreachable.\n\t // if (!parseStates[parseState]) {\n\t // throw invalidParseState()\n\t // }\n\n\t parseStates[parseState]();\n\t } while (token.type !== 'eof')\n\n\t if (typeof reviver === 'function') {\n\t return internalize({'': root}, '', reviver)\n\t }\n\n\t return root\n\t};\n\n\tfunction internalize (holder, name, reviver) {\n\t var value = holder[name];\n\t if (value != null && typeof value === 'object') {\n\t if (Array.isArray(value)) {\n\t for (var i = 0; i < value.length; i++) {\n\t var key = String(i);\n\t var replacement = internalize(value, key, reviver);\n\t if (replacement === undefined) {\n\t delete value[key];\n\t } else {\n\t Object.defineProperty(value, key, {\n\t value: replacement,\n\t writable: true,\n\t enumerable: true,\n\t configurable: true,\n\t });\n\t }\n\t }\n\t } else {\n\t for (var key$1 in value) {\n\t var replacement$1 = internalize(value, key$1, reviver);\n\t if (replacement$1 === undefined) {\n\t delete value[key$1];\n\t } else {\n\t Object.defineProperty(value, key$1, {\n\t value: replacement$1,\n\t writable: true,\n\t enumerable: true,\n\t configurable: true,\n\t });\n\t }\n\t }\n\t }\n\t }\n\n\t return reviver.call(holder, name, value)\n\t}\n\n\tvar lexState;\n\tvar buffer;\n\tvar doubleQuote;\n\tvar sign;\n\tvar c;\n\n\tfunction lex () {\n\t lexState = 'default';\n\t buffer = '';\n\t doubleQuote = false;\n\t sign = 1;\n\n\t for (;;) {\n\t c = peek();\n\n\t // This code is unreachable.\n\t // if (!lexStates[lexState]) {\n\t // throw invalidLexState(lexState)\n\t // }\n\n\t var token = lexStates[lexState]();\n\t if (token) {\n\t return token\n\t }\n\t }\n\t}\n\n\tfunction peek () {\n\t if (source[pos]) {\n\t return String.fromCodePoint(source.codePointAt(pos))\n\t }\n\t}\n\n\tfunction read () {\n\t var c = peek();\n\n\t if (c === '\\n') {\n\t line++;\n\t column = 0;\n\t } else if (c) {\n\t column += c.length;\n\t } else {\n\t column++;\n\t }\n\n\t if (c) {\n\t pos += c.length;\n\t }\n\n\t return c\n\t}\n\n\tvar lexStates = {\n\t default: function default$1 () {\n\t switch (c) {\n\t case '\\t':\n\t case '\\v':\n\t case '\\f':\n\t case ' ':\n\t case '\\u00A0':\n\t case '\\uFEFF':\n\t case '\\n':\n\t case '\\r':\n\t case '\\u2028':\n\t case '\\u2029':\n\t read();\n\t return\n\n\t case '/':\n\t read();\n\t lexState = 'comment';\n\t return\n\n\t case undefined:\n\t read();\n\t return newToken('eof')\n\t }\n\n\t if (util.isSpaceSeparator(c)) {\n\t read();\n\t return\n\t }\n\n\t // This code is unreachable.\n\t // if (!lexStates[parseState]) {\n\t // throw invalidLexState(parseState)\n\t // }\n\n\t return lexStates[parseState]()\n\t },\n\n\t comment: function comment () {\n\t switch (c) {\n\t case '*':\n\t read();\n\t lexState = 'multiLineComment';\n\t return\n\n\t case '/':\n\t read();\n\t lexState = 'singleLineComment';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t multiLineComment: function multiLineComment () {\n\t switch (c) {\n\t case '*':\n\t read();\n\t lexState = 'multiLineCommentAsterisk';\n\t return\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t },\n\n\t multiLineCommentAsterisk: function multiLineCommentAsterisk () {\n\t switch (c) {\n\t case '*':\n\t read();\n\t return\n\n\t case '/':\n\t read();\n\t lexState = 'default';\n\t return\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t lexState = 'multiLineComment';\n\t },\n\n\t singleLineComment: function singleLineComment () {\n\t switch (c) {\n\t case '\\n':\n\t case '\\r':\n\t case '\\u2028':\n\t case '\\u2029':\n\t read();\n\t lexState = 'default';\n\t return\n\n\t case undefined:\n\t read();\n\t return newToken('eof')\n\t }\n\n\t read();\n\t },\n\n\t value: function value () {\n\t switch (c) {\n\t case '{':\n\t case '[':\n\t return newToken('punctuator', read())\n\n\t case 'n':\n\t read();\n\t literal('ull');\n\t return newToken('null', null)\n\n\t case 't':\n\t read();\n\t literal('rue');\n\t return newToken('boolean', true)\n\n\t case 'f':\n\t read();\n\t literal('alse');\n\t return newToken('boolean', false)\n\n\t case '-':\n\t case '+':\n\t if (read() === '-') {\n\t sign = -1;\n\t }\n\n\t lexState = 'sign';\n\t return\n\n\t case '.':\n\t buffer = read();\n\t lexState = 'decimalPointLeading';\n\t return\n\n\t case '0':\n\t buffer = read();\n\t lexState = 'zero';\n\t return\n\n\t case '1':\n\t case '2':\n\t case '3':\n\t case '4':\n\t case '5':\n\t case '6':\n\t case '7':\n\t case '8':\n\t case '9':\n\t buffer = read();\n\t lexState = 'decimalInteger';\n\t return\n\n\t case 'I':\n\t read();\n\t literal('nfinity');\n\t return newToken('numeric', Infinity)\n\n\t case 'N':\n\t read();\n\t literal('aN');\n\t return newToken('numeric', NaN)\n\n\t case '\"':\n\t case \"'\":\n\t doubleQuote = (read() === '\"');\n\t buffer = '';\n\t lexState = 'string';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t identifierNameStartEscape: function identifierNameStartEscape () {\n\t if (c !== 'u') {\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t var u = unicodeEscape();\n\t switch (u) {\n\t case '$':\n\t case '_':\n\t break\n\n\t default:\n\t if (!util.isIdStartChar(u)) {\n\t throw invalidIdentifier()\n\t }\n\n\t break\n\t }\n\n\t buffer += u;\n\t lexState = 'identifierName';\n\t },\n\n\t identifierName: function identifierName () {\n\t switch (c) {\n\t case '$':\n\t case '_':\n\t case '\\u200C':\n\t case '\\u200D':\n\t buffer += read();\n\t return\n\n\t case '\\\\':\n\t read();\n\t lexState = 'identifierNameEscape';\n\t return\n\t }\n\n\t if (util.isIdContinueChar(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('identifier', buffer)\n\t },\n\n\t identifierNameEscape: function identifierNameEscape () {\n\t if (c !== 'u') {\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t var u = unicodeEscape();\n\t switch (u) {\n\t case '$':\n\t case '_':\n\t case '\\u200C':\n\t case '\\u200D':\n\t break\n\n\t default:\n\t if (!util.isIdContinueChar(u)) {\n\t throw invalidIdentifier()\n\t }\n\n\t break\n\t }\n\n\t buffer += u;\n\t lexState = 'identifierName';\n\t },\n\n\t sign: function sign$1 () {\n\t switch (c) {\n\t case '.':\n\t buffer = read();\n\t lexState = 'decimalPointLeading';\n\t return\n\n\t case '0':\n\t buffer = read();\n\t lexState = 'zero';\n\t return\n\n\t case '1':\n\t case '2':\n\t case '3':\n\t case '4':\n\t case '5':\n\t case '6':\n\t case '7':\n\t case '8':\n\t case '9':\n\t buffer = read();\n\t lexState = 'decimalInteger';\n\t return\n\n\t case 'I':\n\t read();\n\t literal('nfinity');\n\t return newToken('numeric', sign * Infinity)\n\n\t case 'N':\n\t read();\n\t literal('aN');\n\t return newToken('numeric', NaN)\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t zero: function zero () {\n\t switch (c) {\n\t case '.':\n\t buffer += read();\n\t lexState = 'decimalPoint';\n\t return\n\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\n\t case 'x':\n\t case 'X':\n\t buffer += read();\n\t lexState = 'hexadecimal';\n\t return\n\t }\n\n\t return newToken('numeric', sign * 0)\n\t },\n\n\t decimalInteger: function decimalInteger () {\n\t switch (c) {\n\t case '.':\n\t buffer += read();\n\t lexState = 'decimalPoint';\n\t return\n\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t decimalPointLeading: function decimalPointLeading () {\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalFraction';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t decimalPoint: function decimalPoint () {\n\t switch (c) {\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalFraction';\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t decimalFraction: function decimalFraction () {\n\t switch (c) {\n\t case 'e':\n\t case 'E':\n\t buffer += read();\n\t lexState = 'decimalExponent';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t decimalExponent: function decimalExponent () {\n\t switch (c) {\n\t case '+':\n\t case '-':\n\t buffer += read();\n\t lexState = 'decimalExponentSign';\n\t return\n\t }\n\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalExponentInteger';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t decimalExponentSign: function decimalExponentSign () {\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t lexState = 'decimalExponentInteger';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t decimalExponentInteger: function decimalExponentInteger () {\n\t if (util.isDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t hexadecimal: function hexadecimal () {\n\t if (util.isHexDigit(c)) {\n\t buffer += read();\n\t lexState = 'hexadecimalInteger';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t hexadecimalInteger: function hexadecimalInteger () {\n\t if (util.isHexDigit(c)) {\n\t buffer += read();\n\t return\n\t }\n\n\t return newToken('numeric', sign * Number(buffer))\n\t },\n\n\t string: function string () {\n\t switch (c) {\n\t case '\\\\':\n\t read();\n\t buffer += escape();\n\t return\n\n\t case '\"':\n\t if (doubleQuote) {\n\t read();\n\t return newToken('string', buffer)\n\t }\n\n\t buffer += read();\n\t return\n\n\t case \"'\":\n\t if (!doubleQuote) {\n\t read();\n\t return newToken('string', buffer)\n\t }\n\n\t buffer += read();\n\t return\n\n\t case '\\n':\n\t case '\\r':\n\t throw invalidChar(read())\n\n\t case '\\u2028':\n\t case '\\u2029':\n\t separatorChar(c);\n\t break\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\t },\n\n\t start: function start () {\n\t switch (c) {\n\t case '{':\n\t case '[':\n\t return newToken('punctuator', read())\n\n\t // This code is unreachable since the default lexState handles eof.\n\t // case undefined:\n\t // return newToken('eof')\n\t }\n\n\t lexState = 'value';\n\t },\n\n\t beforePropertyName: function beforePropertyName () {\n\t switch (c) {\n\t case '$':\n\t case '_':\n\t buffer = read();\n\t lexState = 'identifierName';\n\t return\n\n\t case '\\\\':\n\t read();\n\t lexState = 'identifierNameStartEscape';\n\t return\n\n\t case '}':\n\t return newToken('punctuator', read())\n\n\t case '\"':\n\t case \"'\":\n\t doubleQuote = (read() === '\"');\n\t lexState = 'string';\n\t return\n\t }\n\n\t if (util.isIdStartChar(c)) {\n\t buffer += read();\n\t lexState = 'identifierName';\n\t return\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t afterPropertyName: function afterPropertyName () {\n\t if (c === ':') {\n\t return newToken('punctuator', read())\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t beforePropertyValue: function beforePropertyValue () {\n\t lexState = 'value';\n\t },\n\n\t afterPropertyValue: function afterPropertyValue () {\n\t switch (c) {\n\t case ',':\n\t case '}':\n\t return newToken('punctuator', read())\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t beforeArrayValue: function beforeArrayValue () {\n\t if (c === ']') {\n\t return newToken('punctuator', read())\n\t }\n\n\t lexState = 'value';\n\t },\n\n\t afterArrayValue: function afterArrayValue () {\n\t switch (c) {\n\t case ',':\n\t case ']':\n\t return newToken('punctuator', read())\n\t }\n\n\t throw invalidChar(read())\n\t },\n\n\t end: function end () {\n\t // This code is unreachable since it's handled by the default lexState.\n\t // if (c === undefined) {\n\t // read()\n\t // return newToken('eof')\n\t // }\n\n\t throw invalidChar(read())\n\t },\n\t};\n\n\tfunction newToken (type, value) {\n\t return {\n\t type: type,\n\t value: value,\n\t line: line,\n\t column: column,\n\t }\n\t}\n\n\tfunction literal (s) {\n\t for (var i = 0, list = s; i < list.length; i += 1) {\n\t var c = list[i];\n\n\t var p = peek();\n\n\t if (p !== c) {\n\t throw invalidChar(read())\n\t }\n\n\t read();\n\t }\n\t}\n\n\tfunction escape () {\n\t var c = peek();\n\t switch (c) {\n\t case 'b':\n\t read();\n\t return '\\b'\n\n\t case 'f':\n\t read();\n\t return '\\f'\n\n\t case 'n':\n\t read();\n\t return '\\n'\n\n\t case 'r':\n\t read();\n\t return '\\r'\n\n\t case 't':\n\t read();\n\t return '\\t'\n\n\t case 'v':\n\t read();\n\t return '\\v'\n\n\t case '0':\n\t read();\n\t if (util.isDigit(peek())) {\n\t throw invalidChar(read())\n\t }\n\n\t return '\\0'\n\n\t case 'x':\n\t read();\n\t return hexEscape()\n\n\t case 'u':\n\t read();\n\t return unicodeEscape()\n\n\t case '\\n':\n\t case '\\u2028':\n\t case '\\u2029':\n\t read();\n\t return ''\n\n\t case '\\r':\n\t read();\n\t if (peek() === '\\n') {\n\t read();\n\t }\n\n\t return ''\n\n\t case '1':\n\t case '2':\n\t case '3':\n\t case '4':\n\t case '5':\n\t case '6':\n\t case '7':\n\t case '8':\n\t case '9':\n\t throw invalidChar(read())\n\n\t case undefined:\n\t throw invalidChar(read())\n\t }\n\n\t return read()\n\t}\n\n\tfunction hexEscape () {\n\t var buffer = '';\n\t var c = peek();\n\n\t if (!util.isHexDigit(c)) {\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\n\t c = peek();\n\t if (!util.isHexDigit(c)) {\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\n\t return String.fromCodePoint(parseInt(buffer, 16))\n\t}\n\n\tfunction unicodeEscape () {\n\t var buffer = '';\n\t var count = 4;\n\n\t while (count-- > 0) {\n\t var c = peek();\n\t if (!util.isHexDigit(c)) {\n\t throw invalidChar(read())\n\t }\n\n\t buffer += read();\n\t }\n\n\t return String.fromCodePoint(parseInt(buffer, 16))\n\t}\n\n\tvar parseStates = {\n\t start: function start () {\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t push();\n\t },\n\n\t beforePropertyName: function beforePropertyName () {\n\t switch (token.type) {\n\t case 'identifier':\n\t case 'string':\n\t key = token.value;\n\t parseState = 'afterPropertyName';\n\t return\n\n\t case 'punctuator':\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.value !== '}') {\n\t // throw invalidToken()\n\t // }\n\n\t pop();\n\t return\n\n\t case 'eof':\n\t throw invalidEOF()\n\t }\n\n\t // This code is unreachable since it's handled by the lexState.\n\t // throw invalidToken()\n\t },\n\n\t afterPropertyName: function afterPropertyName () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'punctuator' || token.value !== ':') {\n\t // throw invalidToken()\n\t // }\n\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t parseState = 'beforePropertyValue';\n\t },\n\n\t beforePropertyValue: function beforePropertyValue () {\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t push();\n\t },\n\n\t beforeArrayValue: function beforeArrayValue () {\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t if (token.type === 'punctuator' && token.value === ']') {\n\t pop();\n\t return\n\t }\n\n\t push();\n\t },\n\n\t afterPropertyValue: function afterPropertyValue () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'punctuator') {\n\t // throw invalidToken()\n\t // }\n\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t switch (token.value) {\n\t case ',':\n\t parseState = 'beforePropertyName';\n\t return\n\n\t case '}':\n\t pop();\n\t }\n\n\t // This code is unreachable since it's handled by the lexState.\n\t // throw invalidToken()\n\t },\n\n\t afterArrayValue: function afterArrayValue () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'punctuator') {\n\t // throw invalidToken()\n\t // }\n\n\t if (token.type === 'eof') {\n\t throw invalidEOF()\n\t }\n\n\t switch (token.value) {\n\t case ',':\n\t parseState = 'beforeArrayValue';\n\t return\n\n\t case ']':\n\t pop();\n\t }\n\n\t // This code is unreachable since it's handled by the lexState.\n\t // throw invalidToken()\n\t },\n\n\t end: function end () {\n\t // This code is unreachable since it's handled by the lexState.\n\t // if (token.type !== 'eof') {\n\t // throw invalidToken()\n\t // }\n\t },\n\t};\n\n\tfunction push () {\n\t var value;\n\n\t switch (token.type) {\n\t case 'punctuator':\n\t switch (token.value) {\n\t case '{':\n\t value = {};\n\t break\n\n\t case '[':\n\t value = [];\n\t break\n\t }\n\n\t break\n\n\t case 'null':\n\t case 'boolean':\n\t case 'numeric':\n\t case 'string':\n\t value = token.value;\n\t break\n\n\t // This code is unreachable.\n\t // default:\n\t // throw invalidToken()\n\t }\n\n\t if (root === undefined) {\n\t root = value;\n\t } else {\n\t var parent = stack[stack.length - 1];\n\t if (Array.isArray(parent)) {\n\t parent.push(value);\n\t } else {\n\t Object.defineProperty(parent, key, {\n\t value: value,\n\t writable: true,\n\t enumerable: true,\n\t configurable: true,\n\t });\n\t }\n\t }\n\n\t if (value !== null && typeof value === 'object') {\n\t stack.push(value);\n\n\t if (Array.isArray(value)) {\n\t parseState = 'beforeArrayValue';\n\t } else {\n\t parseState = 'beforePropertyName';\n\t }\n\t } else {\n\t var current = stack[stack.length - 1];\n\t if (current == null) {\n\t parseState = 'end';\n\t } else if (Array.isArray(current)) {\n\t parseState = 'afterArrayValue';\n\t } else {\n\t parseState = 'afterPropertyValue';\n\t }\n\t }\n\t}\n\n\tfunction pop () {\n\t stack.pop();\n\n\t var current = stack[stack.length - 1];\n\t if (current == null) {\n\t parseState = 'end';\n\t } else if (Array.isArray(current)) {\n\t parseState = 'afterArrayValue';\n\t } else {\n\t parseState = 'afterPropertyValue';\n\t }\n\t}\n\n\t// This code is unreachable.\n\t// function invalidParseState () {\n\t// return new Error(`JSON5: invalid parse state '${parseState}'`)\n\t// }\n\n\t// This code is unreachable.\n\t// function invalidLexState (state) {\n\t// return new Error(`JSON5: invalid lex state '${state}'`)\n\t// }\n\n\tfunction invalidChar (c) {\n\t if (c === undefined) {\n\t return syntaxError((\"JSON5: invalid end of input at \" + line + \":\" + column))\n\t }\n\n\t return syntaxError((\"JSON5: invalid character '\" + (formatChar(c)) + \"' at \" + line + \":\" + column))\n\t}\n\n\tfunction invalidEOF () {\n\t return syntaxError((\"JSON5: invalid end of input at \" + line + \":\" + column))\n\t}\n\n\t// This code is unreachable.\n\t// function invalidToken () {\n\t// if (token.type === 'eof') {\n\t// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n\t// }\n\n\t// const c = String.fromCodePoint(token.value.codePointAt(0))\n\t// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n\t// }\n\n\tfunction invalidIdentifier () {\n\t column -= 5;\n\t return syntaxError((\"JSON5: invalid identifier character at \" + line + \":\" + column))\n\t}\n\n\tfunction separatorChar (c) {\n\t console.warn((\"JSON5: '\" + (formatChar(c)) + \"' in strings is not valid ECMAScript; consider escaping\"));\n\t}\n\n\tfunction formatChar (c) {\n\t var replacements = {\n\t \"'\": \"\\\\'\",\n\t '\"': '\\\\\"',\n\t '\\\\': '\\\\\\\\',\n\t '\\b': '\\\\b',\n\t '\\f': '\\\\f',\n\t '\\n': '\\\\n',\n\t '\\r': '\\\\r',\n\t '\\t': '\\\\t',\n\t '\\v': '\\\\v',\n\t '\\0': '\\\\0',\n\t '\\u2028': '\\\\u2028',\n\t '\\u2029': '\\\\u2029',\n\t };\n\n\t if (replacements[c]) {\n\t return replacements[c]\n\t }\n\n\t if (c < ' ') {\n\t var hexString = c.charCodeAt(0).toString(16);\n\t return '\\\\x' + ('00' + hexString).substring(hexString.length)\n\t }\n\n\t return c\n\t}\n\n\tfunction syntaxError (message) {\n\t var err = new SyntaxError(message);\n\t err.lineNumber = line;\n\t err.columnNumber = column;\n\t return err\n\t}\n\n\tvar stringify = function stringify (value, replacer, space) {\n\t var stack = [];\n\t var indent = '';\n\t var propertyList;\n\t var replacerFunc;\n\t var gap = '';\n\t var quote;\n\n\t if (\n\t replacer != null &&\n\t typeof replacer === 'object' &&\n\t !Array.isArray(replacer)\n\t ) {\n\t space = replacer.space;\n\t quote = replacer.quote;\n\t replacer = replacer.replacer;\n\t }\n\n\t if (typeof replacer === 'function') {\n\t replacerFunc = replacer;\n\t } else if (Array.isArray(replacer)) {\n\t propertyList = [];\n\t for (var i = 0, list = replacer; i < list.length; i += 1) {\n\t var v = list[i];\n\n\t var item = (void 0);\n\n\t if (typeof v === 'string') {\n\t item = v;\n\t } else if (\n\t typeof v === 'number' ||\n\t v instanceof String ||\n\t v instanceof Number\n\t ) {\n\t item = String(v);\n\t }\n\n\t if (item !== undefined && propertyList.indexOf(item) < 0) {\n\t propertyList.push(item);\n\t }\n\t }\n\t }\n\n\t if (space instanceof Number) {\n\t space = Number(space);\n\t } else if (space instanceof String) {\n\t space = String(space);\n\t }\n\n\t if (typeof space === 'number') {\n\t if (space > 0) {\n\t space = Math.min(10, Math.floor(space));\n\t gap = ' '.substr(0, space);\n\t }\n\t } else if (typeof space === 'string') {\n\t gap = space.substr(0, 10);\n\t }\n\n\t return serializeProperty('', {'': value})\n\n\t function serializeProperty (key, holder) {\n\t var value = holder[key];\n\t if (value != null) {\n\t if (typeof value.toJSON5 === 'function') {\n\t value = value.toJSON5(key);\n\t } else if (typeof value.toJSON === 'function') {\n\t value = value.toJSON(key);\n\t }\n\t }\n\n\t if (replacerFunc) {\n\t value = replacerFunc.call(holder, key, value);\n\t }\n\n\t if (value instanceof Number) {\n\t value = Number(value);\n\t } else if (value instanceof String) {\n\t value = String(value);\n\t } else if (value instanceof Boolean) {\n\t value = value.valueOf();\n\t }\n\n\t switch (value) {\n\t case null: return 'null'\n\t case true: return 'true'\n\t case false: return 'false'\n\t }\n\n\t if (typeof value === 'string') {\n\t return quoteString(value, false)\n\t }\n\n\t if (typeof value === 'number') {\n\t return String(value)\n\t }\n\n\t if (typeof value === 'object') {\n\t return Array.isArray(value) ? serializeArray(value) : serializeObject(value)\n\t }\n\n\t return undefined\n\t }\n\n\t function quoteString (value) {\n\t var quotes = {\n\t \"'\": 0.1,\n\t '\"': 0.2,\n\t };\n\n\t var replacements = {\n\t \"'\": \"\\\\'\",\n\t '\"': '\\\\\"',\n\t '\\\\': '\\\\\\\\',\n\t '\\b': '\\\\b',\n\t '\\f': '\\\\f',\n\t '\\n': '\\\\n',\n\t '\\r': '\\\\r',\n\t '\\t': '\\\\t',\n\t '\\v': '\\\\v',\n\t '\\0': '\\\\0',\n\t '\\u2028': '\\\\u2028',\n\t '\\u2029': '\\\\u2029',\n\t };\n\n\t var product = '';\n\n\t for (var i = 0; i < value.length; i++) {\n\t var c = value[i];\n\t switch (c) {\n\t case \"'\":\n\t case '\"':\n\t quotes[c]++;\n\t product += c;\n\t continue\n\n\t case '\\0':\n\t if (util.isDigit(value[i + 1])) {\n\t product += '\\\\x00';\n\t continue\n\t }\n\t }\n\n\t if (replacements[c]) {\n\t product += replacements[c];\n\t continue\n\t }\n\n\t if (c < ' ') {\n\t var hexString = c.charCodeAt(0).toString(16);\n\t product += '\\\\x' + ('00' + hexString).substring(hexString.length);\n\t continue\n\t }\n\n\t product += c;\n\t }\n\n\t var quoteChar = quote || Object.keys(quotes).reduce(function (a, b) { return (quotes[a] < quotes[b]) ? a : b; });\n\n\t product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);\n\n\t return quoteChar + product + quoteChar\n\t }\n\n\t function serializeObject (value) {\n\t if (stack.indexOf(value) >= 0) {\n\t throw TypeError('Converting circular structure to JSON5')\n\t }\n\n\t stack.push(value);\n\n\t var stepback = indent;\n\t indent = indent + gap;\n\n\t var keys = propertyList || Object.keys(value);\n\t var partial = [];\n\t for (var i = 0, list = keys; i < list.length; i += 1) {\n\t var key = list[i];\n\n\t var propertyString = serializeProperty(key, value);\n\t if (propertyString !== undefined) {\n\t var member = serializeKey(key) + ':';\n\t if (gap !== '') {\n\t member += ' ';\n\t }\n\t member += propertyString;\n\t partial.push(member);\n\t }\n\t }\n\n\t var final;\n\t if (partial.length === 0) {\n\t final = '{}';\n\t } else {\n\t var properties;\n\t if (gap === '') {\n\t properties = partial.join(',');\n\t final = '{' + properties + '}';\n\t } else {\n\t var separator = ',\\n' + indent;\n\t properties = partial.join(separator);\n\t final = '{\\n' + indent + properties + ',\\n' + stepback + '}';\n\t }\n\t }\n\n\t stack.pop();\n\t indent = stepback;\n\t return final\n\t }\n\n\t function serializeKey (key) {\n\t if (key.length === 0) {\n\t return quoteString(key, true)\n\t }\n\n\t var firstChar = String.fromCodePoint(key.codePointAt(0));\n\t if (!util.isIdStartChar(firstChar)) {\n\t return quoteString(key, true)\n\t }\n\n\t for (var i = firstChar.length; i < key.length; i++) {\n\t if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {\n\t return quoteString(key, true)\n\t }\n\t }\n\n\t return key\n\t }\n\n\t function serializeArray (value) {\n\t if (stack.indexOf(value) >= 0) {\n\t throw TypeError('Converting circular structure to JSON5')\n\t }\n\n\t stack.push(value);\n\n\t var stepback = indent;\n\t indent = indent + gap;\n\n\t var partial = [];\n\t for (var i = 0; i < value.length; i++) {\n\t var propertyString = serializeProperty(String(i), value);\n\t partial.push((propertyString !== undefined) ? propertyString : 'null');\n\t }\n\n\t var final;\n\t if (partial.length === 0) {\n\t final = '[]';\n\t } else {\n\t if (gap === '') {\n\t var properties = partial.join(',');\n\t final = '[' + properties + ']';\n\t } else {\n\t var separator = ',\\n' + indent;\n\t var properties$1 = partial.join(separator);\n\t final = '[\\n' + indent + properties$1 + ',\\n' + stepback + ']';\n\t }\n\t }\n\n\t stack.pop();\n\t indent = stepback;\n\t return final\n\t }\n\t};\n\n\tvar JSON5 = {\n\t parse: parse,\n\t stringify: stringify,\n\t};\n\n\tvar lib = JSON5;\n\n\tvar es5 = lib;\n\n\treturn es5;\n\n})));\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.memoryStorageDriver = factory());\n}(this, function () { 'use strict';\n\n function getSerializerPromise(localForageInstance) {\n if (getSerializerPromise.result) {\n return getSerializerPromise.result;\n }\n if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {\n Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));\n }\n getSerializerPromise.result = localForageInstance.getSerializer();\n return getSerializerPromise.result;\n }\n\n function executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n }\n\n var storageRepository = {};\n\n // Config the localStorage backend, using options set in the config.\n function _initStorage(options) {\n var self = this;\n\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n var database = storageRepository[dbInfo.name] = storageRepository[dbInfo.name] || {};\n var table = database[dbInfo.storeName] = database[dbInfo.storeName] || {};\n dbInfo.db = table;\n\n self._dbInfo = dbInfo;\n\n return getSerializerPromise(self).then(function (serializer) {\n dbInfo.serializer = serializer;\n });\n }\n\n function clear(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n delete db[key];\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function getItem(key, callback) {\n var self = this;\n\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n var result = db[key];\n\n if (result) {\n result = self._dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function iterate(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n\n var iterationNumber = 1;\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n var value = db[key];\n\n if (value) {\n value = self._dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key, iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function key(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n var result = null;\n var index = 0;\n\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n if (n === index) {\n result = key;\n break;\n }\n index++;\n }\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function keys(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n var keys = [];\n\n for (var key in db) {\n if (db.hasOwnProperty(key)) {\n keys.push(key);\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function length(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function removeItem(key, callback) {\n var self = this;\n\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n var promise = self.ready().then(function () {\n var db = self._dbInfo.db;\n if (db.hasOwnProperty(key)) {\n delete db[key];\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n function setItem(key, value, callback) {\n var self = this;\n\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n function serializeAsync(value) {\n return new Promise(function (resolve, reject) {\n self._dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n resolve(value);\n }\n });\n });\n }\n\n return serializeAsync(value).then(function (value) {\n var db = self._dbInfo.db;\n db[key] = value;\n return originalValue;\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n }\n\n var memoryStorageDriver = {\n _driver: 'memoryStorageDriver',\n _initStorage: _initStorage,\n // _supports: function() { return true; }\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys\n };\n\n return memoryStorageDriver;\n\n}));","/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n var db = openreq.result;\n db.onversionchange = function (e) {\n // Triggered when the database is modified (e.g. adding an objectStore) or\n // deleted (even when initiated by other sessions in different tabs).\n // Closing the connection here prevents those operations from being blocked.\n // If the database is accessed again later by this instance, the connection\n // will be reopened or the database recreated as needed.\n e.target.close();\n };\n resolve(db);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(req.error);\n };\n\n req.onblocked = function () {\n // Closing all open connections in onversionchange handler should prevent this situation, but if\n // we do get here, it just means the request remains pending - eventually it will succeed or error\n console.warn('dropInstance blocked for database \"' + options.name + '\" until all open connections are closed');\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n","'use strict';\n\nfunction hasKey(obj, keys) {\n\tvar o = obj;\n\tkeys.slice(0, -1).forEach(function (key) {\n\t\to = o[key] || {};\n\t});\n\n\tvar key = keys[keys.length - 1];\n\treturn key in o;\n}\n\nfunction isNumber(x) {\n\tif (typeof x === 'number') { return true; }\n\tif ((/^0x[0-9a-f]+$/i).test(x)) { return true; }\n\treturn (/^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(e[-+]?\\d+)?$/).test(x);\n}\n\nfunction isConstructorOrProto(obj, key) {\n\treturn (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__';\n}\n\nmodule.exports = function (args, opts) {\n\tif (!opts) { opts = {}; }\n\n\tvar flags = {\n\t\tbools: {},\n\t\tstrings: {},\n\t\tunknownFn: null,\n\t};\n\n\tif (typeof opts.unknown === 'function') {\n\t\tflags.unknownFn = opts.unknown;\n\t}\n\n\tif (typeof opts.boolean === 'boolean' && opts.boolean) {\n\t\tflags.allBools = true;\n\t} else {\n\t\t[].concat(opts.boolean).filter(Boolean).forEach(function (key) {\n\t\t\tflags.bools[key] = true;\n\t\t});\n\t}\n\n\tvar aliases = {};\n\n\tfunction aliasIsBoolean(key) {\n\t\treturn aliases[key].some(function (x) {\n\t\t\treturn flags.bools[x];\n\t\t});\n\t}\n\n\tObject.keys(opts.alias || {}).forEach(function (key) {\n\t\taliases[key] = [].concat(opts.alias[key]);\n\t\taliases[key].forEach(function (x) {\n\t\t\taliases[x] = [key].concat(aliases[key].filter(function (y) {\n\t\t\t\treturn x !== y;\n\t\t\t}));\n\t\t});\n\t});\n\n\t[].concat(opts.string).filter(Boolean).forEach(function (key) {\n\t\tflags.strings[key] = true;\n\t\tif (aliases[key]) {\n\t\t\t[].concat(aliases[key]).forEach(function (k) {\n\t\t\t\tflags.strings[k] = true;\n\t\t\t});\n\t\t}\n\t});\n\n\tvar defaults = opts.default || {};\n\n\tvar argv = { _: [] };\n\n\tfunction argDefined(key, arg) {\n\t\treturn (flags.allBools && (/^--[^=]+$/).test(arg))\n\t\t\t|| flags.strings[key]\n\t\t\t|| flags.bools[key]\n\t\t\t|| aliases[key];\n\t}\n\n\tfunction setKey(obj, keys, value) {\n\t\tvar o = obj;\n\t\tfor (var i = 0; i < keys.length - 1; i++) {\n\t\t\tvar key = keys[i];\n\t\t\tif (isConstructorOrProto(o, key)) { return; }\n\t\t\tif (o[key] === undefined) { o[key] = {}; }\n\t\t\tif (\n\t\t\t\to[key] === Object.prototype\n\t\t\t\t|| o[key] === Number.prototype\n\t\t\t\t|| o[key] === String.prototype\n\t\t\t) {\n\t\t\t\to[key] = {};\n\t\t\t}\n\t\t\tif (o[key] === Array.prototype) { o[key] = []; }\n\t\t\to = o[key];\n\t\t}\n\n\t\tvar lastKey = keys[keys.length - 1];\n\t\tif (isConstructorOrProto(o, lastKey)) { return; }\n\t\tif (\n\t\t\to === Object.prototype\n\t\t\t|| o === Number.prototype\n\t\t\t|| o === String.prototype\n\t\t) {\n\t\t\to = {};\n\t\t}\n\t\tif (o === Array.prototype) { o = []; }\n\t\tif (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') {\n\t\t\to[lastKey] = value;\n\t\t} else if (Array.isArray(o[lastKey])) {\n\t\t\to[lastKey].push(value);\n\t\t} else {\n\t\t\to[lastKey] = [o[lastKey], value];\n\t\t}\n\t}\n\n\tfunction setArg(key, val, arg) {\n\t\tif (arg && flags.unknownFn && !argDefined(key, arg)) {\n\t\t\tif (flags.unknownFn(arg) === false) { return; }\n\t\t}\n\n\t\tvar value = !flags.strings[key] && isNumber(val)\n\t\t\t? Number(val)\n\t\t\t: val;\n\t\tsetKey(argv, key.split('.'), value);\n\n\t\t(aliases[key] || []).forEach(function (x) {\n\t\t\tsetKey(argv, x.split('.'), value);\n\t\t});\n\t}\n\n\tObject.keys(flags.bools).forEach(function (key) {\n\t\tsetArg(key, defaults[key] === undefined ? false : defaults[key]);\n\t});\n\n\tvar notFlags = [];\n\n\tif (args.indexOf('--') !== -1) {\n\t\tnotFlags = args.slice(args.indexOf('--') + 1);\n\t\targs = args.slice(0, args.indexOf('--'));\n\t}\n\n\tfor (var i = 0; i < args.length; i++) {\n\t\tvar arg = args[i];\n\t\tvar key;\n\t\tvar next;\n\n\t\tif ((/^--.+=/).test(arg)) {\n\t\t\t// Using [\\s\\S] instead of . because js doesn't support the\n\t\t\t// 'dotall' regex modifier. See:\n\t\t\t// http://stackoverflow.com/a/1068308/13216\n\t\t\tvar m = arg.match(/^--([^=]+)=([\\s\\S]*)$/);\n\t\t\tkey = m[1];\n\t\t\tvar value = m[2];\n\t\t\tif (flags.bools[key]) {\n\t\t\t\tvalue = value !== 'false';\n\t\t\t}\n\t\t\tsetArg(key, value, arg);\n\t\t} else if ((/^--no-.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--no-(.+)/)[1];\n\t\t\tsetArg(key, false, arg);\n\t\t} else if ((/^--.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--(.+)/)[1];\n\t\t\tnext = args[i + 1];\n\t\t\tif (\n\t\t\t\tnext !== undefined\n\t\t\t\t&& !(/^(-|--)[^-]/).test(next)\n\t\t\t\t&& !flags.bools[key]\n\t\t\t\t&& !flags.allBools\n\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t) {\n\t\t\t\tsetArg(key, next, arg);\n\t\t\t\ti += 1;\n\t\t\t} else if ((/^(true|false)$/).test(next)) {\n\t\t\t\tsetArg(key, next === 'true', arg);\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t}\n\t\t} else if ((/^-[^-]+/).test(arg)) {\n\t\t\tvar letters = arg.slice(1, -1).split('');\n\n\t\t\tvar broken = false;\n\t\t\tfor (var j = 0; j < letters.length; j++) {\n\t\t\t\tnext = arg.slice(j + 2);\n\n\t\t\t\tif (next === '-') {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') {\n\t\t\t\t\tsetArg(letters[j], next.slice(1), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(/[A-Za-z]/).test(letters[j])\n\t\t\t\t\t&& (/-?\\d+(\\.\\d*)?(e-?\\d+)?$/).test(next)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (letters[j + 1] && letters[j + 1].match(/\\W/)) {\n\t\t\t\t\tsetArg(letters[j], arg.slice(j + 2), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tkey = arg.slice(-1)[0];\n\t\t\tif (!broken && key !== '-') {\n\t\t\t\tif (\n\t\t\t\t\targs[i + 1]\n\t\t\t\t\t&& !(/^(-|--)[^-]/).test(args[i + 1])\n\t\t\t\t\t&& !flags.bools[key]\n\t\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(key, args[i + 1], arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) {\n\t\t\t\t\tsetArg(key, args[i + 1] === 'true', arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (!flags.unknownFn || flags.unknownFn(arg) !== false) {\n\t\t\t\targv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));\n\t\t\t}\n\t\t\tif (opts.stopEarly) {\n\t\t\t\targv._.push.apply(argv._, args.slice(i + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tObject.keys(defaults).forEach(function (k) {\n\t\tif (!hasKey(argv, k.split('.'))) {\n\t\t\tsetKey(argv, k.split('.'), defaults[k]);\n\n\t\t\t(aliases[k] || []).forEach(function (x) {\n\t\t\t\tsetKey(argv, x.split('.'), defaults[k]);\n\t\t\t});\n\t\t}\n\t});\n\n\tif (opts['--']) {\n\t\targv['--'] = notFlags.slice();\n\t} else {\n\t\tnotFlags.forEach(function (k) {\n\t\t\targv._.push(k);\n\t\t});\n\t}\n\n\treturn argv;\n};\n","(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n\ttypeof define === 'function' && define.amd ? define(['exports'], factory) :\n\t(factory((global.Mock = global.Mock || {})));\n}(this, (function (exports) { 'use strict';\n\nvar commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nvar requiresPort = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) { return false; }\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n\nvar has = Object.prototype.hasOwnProperty;\nvar undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) { continue; }\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) { prefix = '?'; }\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) { continue; }\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nvar stringify = querystringify;\nvar parse = querystring;\n\nvar querystringify_1 = {\n\tstringify: stringify,\n\tparse: parse\n};\n\nvar CRHTLF = /[\\n\\r\\t]/g;\nvar slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//;\nvar protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i;\nvar windowsDriveLetter = /^[a-zA-Z]:/;\nvar whitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/;\n\n/**\n * Trim a given string.\n *\n * @param {String} str String to trim.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(whitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') { globalVar = window; }\n else if (typeof commonjsGlobal !== 'undefined') { globalVar = commonjsGlobal; }\n else if (typeof self !== 'undefined') { globalVar = self; }\n else { globalVar = {}; }\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) { delete finaldestination[key]; }\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) { continue; }\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4];\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') { return base; }\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) { unshift = true; }\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) { path.unshift(''); }\n if (last === '.' || last === '..') { path.push(''); }\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) { parser = querystringify_1.parse; }\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) { url[key] = url[key].toLowerCase(); }\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) { url.query = parser(url.query); }\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!requiresPort(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || querystringify_1.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!requiresPort(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) { value += ':'+ url.port; }\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (/:\\d+$/.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) { url[ins[1]] = url[ins[1]].toLowerCase(); }\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) { stringify = querystringify_1.stringify; }\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') { protocol += ':'; }\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) { result += ':'+ url.password; }\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':') { host += ':'; }\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) { result += '?' !== query.charAt(0) ? '?'+ query : query; }\n\n if (url.hash) { result += url.hash; }\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = querystringify_1;\n\nvar urlParse = Url;\n\n/*\n * This delay allows the thread to finish assigning its on* methods\n * before invoking the delay callback. This is purely a timing hack.\n * http://geekabyte.blogspot.com/2014/01/javascript-effect-of-setting-settimeout.html\n *\n * @param {callback: function} the callback which will be invoked after the timeout\n * @parma {context: object} the context in which to invoke the function\n */\nfunction delay(callback, context) {\n setTimeout(function (timeoutContext) { return callback.call(timeoutContext); }, 4, context);\n}\n\nfunction log(method, message) {\n /* eslint-disable no-console */\n if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'test') {\n console[method].call(null, message);\n }\n /* eslint-enable no-console */\n}\n\nfunction reject(array, callback) {\n if ( array === void 0 ) array = [];\n\n var results = [];\n array.forEach(function (itemInArray) {\n if (!callback(itemInArray)) {\n results.push(itemInArray);\n }\n });\n\n return results;\n}\n\nfunction filter(array, callback) {\n if ( array === void 0 ) array = [];\n\n var results = [];\n array.forEach(function (itemInArray) {\n if (callback(itemInArray)) {\n results.push(itemInArray);\n }\n });\n\n return results;\n}\n\n/*\n * EventTarget is an interface implemented by objects that can\n * receive events and may have listeners for them.\n *\n * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget\n */\nvar EventTarget = function EventTarget() {\n this.listeners = {};\n};\n\n/*\n * Ties a listener function to an event type which can later be invoked via the\n * dispatchEvent method.\n *\n * @param {string} type - the type of event (ie: 'open', 'message', etc.)\n * @param {function} listener - callback function to invoke when an event is dispatched matching the type\n * @param {boolean} useCapture - N/A TODO: implement useCapture functionality\n */\nEventTarget.prototype.addEventListener = function addEventListener (type, listener /* , useCapture */) {\n if (typeof listener === 'function') {\n if (!Array.isArray(this.listeners[type])) {\n this.listeners[type] = [];\n }\n\n // Only add the same function once\n if (filter(this.listeners[type], function (item) { return item === listener; }).length === 0) {\n this.listeners[type].push(listener);\n }\n }\n};\n\n/*\n * Removes the listener so it will no longer be invoked via the dispatchEvent method.\n *\n * @param {string} type - the type of event (ie: 'open', 'message', etc.)\n * @param {function} listener - callback function to invoke when an event is dispatched matching the type\n * @param {boolean} useCapture - N/A TODO: implement useCapture functionality\n */\nEventTarget.prototype.removeEventListener = function removeEventListener (type, removingListener /* , useCapture */) {\n var arrayOfListeners = this.listeners[type];\n this.listeners[type] = reject(arrayOfListeners, function (listener) { return listener === removingListener; });\n};\n\n/*\n * Invokes all listener functions that are listening to the given event.type property. Each\n * listener will be passed the event as the first argument.\n *\n * @param {object} event - event object which will be passed to all listeners of the event.type property\n */\nEventTarget.prototype.dispatchEvent = function dispatchEvent (event) {\n var this$1 = this;\n var customArguments = [], len = arguments.length - 1;\n while ( len-- > 0 ) customArguments[ len ] = arguments[ len + 1 ];\n\n var eventName = event.type;\n var listeners = this.listeners[eventName];\n\n if (!Array.isArray(listeners)) {\n return false;\n }\n\n listeners.forEach(function (listener) {\n if (customArguments.length > 0) {\n listener.apply(this$1, customArguments);\n } else {\n listener.call(this$1, event);\n }\n });\n\n return true;\n};\n\nfunction trimQueryPartFromURL(url) {\n var queryIndex = url.indexOf('?');\n return queryIndex >= 0 ? url.slice(0, queryIndex) : url;\n}\n\n/*\n * The network bridge is a way for the mock websocket object to 'communicate' with\n * all available servers. This is a singleton object so it is important that you\n * clean up urlMap whenever you are finished.\n */\nvar NetworkBridge = function NetworkBridge() {\n this.urlMap = {};\n};\n\n/*\n * Attaches a websocket object to the urlMap hash so that it can find the server\n * it is connected to and the server in turn can find it.\n *\n * @param {object} websocket - websocket object to add to the urlMap hash\n * @param {string} url\n */\nNetworkBridge.prototype.attachWebSocket = function attachWebSocket (websocket, url) {\n var serverURL = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverURL];\n\n if (connectionLookup && connectionLookup.server && connectionLookup.websockets.indexOf(websocket) === -1) {\n connectionLookup.websockets.push(websocket);\n return connectionLookup.server;\n }\n};\n\n/*\n * Attaches a websocket to a room\n */\nNetworkBridge.prototype.addMembershipToRoom = function addMembershipToRoom (websocket, room) {\n var connectionLookup = this.urlMap[trimQueryPartFromURL(websocket.url)];\n\n if (connectionLookup && connectionLookup.server && connectionLookup.websockets.indexOf(websocket) !== -1) {\n if (!connectionLookup.roomMemberships[room]) {\n connectionLookup.roomMemberships[room] = [];\n }\n\n connectionLookup.roomMemberships[room].push(websocket);\n }\n};\n\n/*\n * Attaches a server object to the urlMap hash so that it can find a websockets\n * which are connected to it and so that websockets can in turn can find it.\n *\n * @param {object} server - server object to add to the urlMap hash\n * @param {string} url\n */\nNetworkBridge.prototype.attachServer = function attachServer (server, url) {\n var serverUrl = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverUrl];\n\n if (!connectionLookup) {\n this.urlMap[serverUrl] = {\n server: server,\n websockets: [],\n roomMemberships: {}\n };\n\n return server;\n }\n};\n\n/*\n * Finds the server which is 'running' on the given url.\n *\n * @param {string} url - the url to use to find which server is running on it\n */\nNetworkBridge.prototype.serverLookup = function serverLookup (url) {\n var serverURL = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverURL];\n\n if (connectionLookup) {\n return connectionLookup.server;\n }\n};\n\n/*\n * Finds all websockets which is 'listening' on the given url.\n *\n * @param {string} url - the url to use to find all websockets which are associated with it\n * @param {string} room - if a room is provided, will only return sockets in this room\n * @param {class} broadcaster - socket that is broadcasting and is to be excluded from the lookup\n */\nNetworkBridge.prototype.websocketsLookup = function websocketsLookup (url, room, broadcaster) {\n var serverURL = trimQueryPartFromURL(url);\n var websockets;\n var connectionLookup = this.urlMap[serverURL];\n\n websockets = connectionLookup ? connectionLookup.websockets : [];\n\n if (room) {\n var members = connectionLookup.roomMemberships[room];\n websockets = members || [];\n }\n\n return broadcaster ? websockets.filter(function (websocket) { return websocket !== broadcaster; }) : websockets;\n};\n\n/*\n * Removes the entry associated with the url.\n *\n * @param {string} url\n */\nNetworkBridge.prototype.removeServer = function removeServer (url) {\n delete this.urlMap[trimQueryPartFromURL(url)];\n};\n\n/*\n * Removes the individual websocket from the map of associated websockets.\n *\n * @param {object} websocket - websocket object to remove from the url map\n * @param {string} url\n */\nNetworkBridge.prototype.removeWebSocket = function removeWebSocket (websocket, url) {\n var serverURL = trimQueryPartFromURL(url);\n var connectionLookup = this.urlMap[serverURL];\n\n if (connectionLookup) {\n connectionLookup.websockets = reject(connectionLookup.websockets, function (socket) { return socket === websocket; });\n }\n};\n\n/*\n * Removes a websocket from a room\n */\nNetworkBridge.prototype.removeMembershipFromRoom = function removeMembershipFromRoom (websocket, room) {\n var connectionLookup = this.urlMap[trimQueryPartFromURL(websocket.url)];\n var memberships = connectionLookup.roomMemberships[room];\n\n if (connectionLookup && memberships !== null) {\n connectionLookup.roomMemberships[room] = reject(memberships, function (socket) { return socket === websocket; });\n }\n};\n\nvar networkBridge = new NetworkBridge(); // Note: this is a singleton\n\n/*\n * https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent\n */\nvar CLOSE_CODES = {\n CLOSE_NORMAL: 1000,\n CLOSE_GOING_AWAY: 1001,\n CLOSE_PROTOCOL_ERROR: 1002,\n CLOSE_UNSUPPORTED: 1003,\n CLOSE_NO_STATUS: 1005,\n CLOSE_ABNORMAL: 1006,\n UNSUPPORTED_DATA: 1007,\n POLICY_VIOLATION: 1008,\n CLOSE_TOO_LARGE: 1009,\n MISSING_EXTENSION: 1010,\n INTERNAL_ERROR: 1011,\n SERVICE_RESTART: 1012,\n TRY_AGAIN_LATER: 1013,\n TLS_HANDSHAKE: 1015\n};\n\nvar ERROR_PREFIX = {\n CONSTRUCTOR_ERROR: \"Failed to construct 'WebSocket':\",\n CLOSE_ERROR: \"Failed to execute 'close' on 'WebSocket':\",\n EVENT: {\n CONSTRUCT: \"Failed to construct 'Event':\",\n MESSAGE: \"Failed to construct 'MessageEvent':\",\n CLOSE: \"Failed to construct 'CloseEvent':\"\n }\n};\n\nvar EventPrototype = function EventPrototype () {};\n\nEventPrototype.prototype.stopPropagation = function stopPropagation () {};\nEventPrototype.prototype.stopImmediatePropagation = function stopImmediatePropagation () {};\n\n// if no arguments are passed then the type is set to \"undefined\" on\n// chrome and safari.\nEventPrototype.prototype.initEvent = function initEvent (type, bubbles, cancelable) {\n if ( type === void 0 ) type = 'undefined';\n if ( bubbles === void 0 ) bubbles = false;\n if ( cancelable === void 0 ) cancelable = false;\n\n this.type = \"\" + type;\n this.bubbles = Boolean(bubbles);\n this.cancelable = Boolean(cancelable);\n};\n\nvar Event = (function (EventPrototype$$1) {\n function Event(type, eventInitConfig) {\n if ( eventInitConfig === void 0 ) eventInitConfig = {};\n\n EventPrototype$$1.call(this);\n\n if (!type) {\n throw new TypeError(((ERROR_PREFIX.EVENT_ERROR) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (typeof eventInitConfig !== 'object') {\n throw new TypeError(((ERROR_PREFIX.EVENT_ERROR) + \" parameter 2 ('eventInitDict') is not an object.\"));\n }\n\n var bubbles = eventInitConfig.bubbles;\n var cancelable = eventInitConfig.cancelable;\n\n this.type = \"\" + type;\n this.timeStamp = Date.now();\n this.target = null;\n this.srcElement = null;\n this.returnValue = true;\n this.isTrusted = false;\n this.eventPhase = 0;\n this.defaultPrevented = false;\n this.currentTarget = null;\n this.cancelable = cancelable ? Boolean(cancelable) : false;\n this.cancelBubble = false;\n this.bubbles = bubbles ? Boolean(bubbles) : false;\n }\n\n if ( EventPrototype$$1 ) Event.__proto__ = EventPrototype$$1;\n Event.prototype = Object.create( EventPrototype$$1 && EventPrototype$$1.prototype );\n Event.prototype.constructor = Event;\n\n return Event;\n}(EventPrototype));\n\nvar MessageEvent = (function (EventPrototype$$1) {\n function MessageEvent(type, eventInitConfig) {\n if ( eventInitConfig === void 0 ) eventInitConfig = {};\n\n EventPrototype$$1.call(this);\n\n if (!type) {\n throw new TypeError(((ERROR_PREFIX.EVENT.MESSAGE) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (typeof eventInitConfig !== 'object') {\n throw new TypeError(((ERROR_PREFIX.EVENT.MESSAGE) + \" parameter 2 ('eventInitDict') is not an object\"));\n }\n\n var bubbles = eventInitConfig.bubbles;\n var cancelable = eventInitConfig.cancelable;\n var data = eventInitConfig.data;\n var origin = eventInitConfig.origin;\n var lastEventId = eventInitConfig.lastEventId;\n var ports = eventInitConfig.ports;\n\n this.type = \"\" + type;\n this.timeStamp = Date.now();\n this.target = null;\n this.srcElement = null;\n this.returnValue = true;\n this.isTrusted = false;\n this.eventPhase = 0;\n this.defaultPrevented = false;\n this.currentTarget = null;\n this.cancelable = cancelable ? Boolean(cancelable) : false;\n this.canncelBubble = false;\n this.bubbles = bubbles ? Boolean(bubbles) : false;\n this.origin = \"\" + origin;\n this.ports = typeof ports === 'undefined' ? null : ports;\n this.data = typeof data === 'undefined' ? null : data;\n this.lastEventId = \"\" + (lastEventId || '');\n }\n\n if ( EventPrototype$$1 ) MessageEvent.__proto__ = EventPrototype$$1;\n MessageEvent.prototype = Object.create( EventPrototype$$1 && EventPrototype$$1.prototype );\n MessageEvent.prototype.constructor = MessageEvent;\n\n return MessageEvent;\n}(EventPrototype));\n\nvar CloseEvent = (function (EventPrototype$$1) {\n function CloseEvent(type, eventInitConfig) {\n if ( eventInitConfig === void 0 ) eventInitConfig = {};\n\n EventPrototype$$1.call(this);\n\n if (!type) {\n throw new TypeError(((ERROR_PREFIX.EVENT.CLOSE) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (typeof eventInitConfig !== 'object') {\n throw new TypeError(((ERROR_PREFIX.EVENT.CLOSE) + \" parameter 2 ('eventInitDict') is not an object\"));\n }\n\n var bubbles = eventInitConfig.bubbles;\n var cancelable = eventInitConfig.cancelable;\n var code = eventInitConfig.code;\n var reason = eventInitConfig.reason;\n var wasClean = eventInitConfig.wasClean;\n\n this.type = \"\" + type;\n this.timeStamp = Date.now();\n this.target = null;\n this.srcElement = null;\n this.returnValue = true;\n this.isTrusted = false;\n this.eventPhase = 0;\n this.defaultPrevented = false;\n this.currentTarget = null;\n this.cancelable = cancelable ? Boolean(cancelable) : false;\n this.cancelBubble = false;\n this.bubbles = bubbles ? Boolean(bubbles) : false;\n this.code = typeof code === 'number' ? parseInt(code, 10) : 0;\n this.reason = \"\" + (reason || '');\n this.wasClean = wasClean ? Boolean(wasClean) : false;\n }\n\n if ( EventPrototype$$1 ) CloseEvent.__proto__ = EventPrototype$$1;\n CloseEvent.prototype = Object.create( EventPrototype$$1 && EventPrototype$$1.prototype );\n CloseEvent.prototype.constructor = CloseEvent;\n\n return CloseEvent;\n}(EventPrototype));\n\n/*\n * Creates an Event object and extends it to allow full modification of\n * its properties.\n *\n * @param {object} config - within config you will need to pass type and optionally target\n */\nfunction createEvent(config) {\n var type = config.type;\n var target = config.target;\n var eventObject = new Event(type);\n\n if (target) {\n eventObject.target = target;\n eventObject.srcElement = target;\n eventObject.currentTarget = target;\n }\n\n return eventObject;\n}\n\n/*\n * Creates a MessageEvent object and extends it to allow full modification of\n * its properties.\n *\n * @param {object} config - within config: type, origin, data and optionally target\n */\nfunction createMessageEvent(config) {\n var type = config.type;\n var origin = config.origin;\n var data = config.data;\n var target = config.target;\n var messageEvent = new MessageEvent(type, {\n data: data,\n origin: origin\n });\n\n if (target) {\n messageEvent.target = target;\n messageEvent.srcElement = target;\n messageEvent.currentTarget = target;\n }\n\n return messageEvent;\n}\n\n/*\n * Creates a CloseEvent object and extends it to allow full modification of\n * its properties.\n *\n * @param {object} config - within config: type and optionally target, code, and reason\n */\nfunction createCloseEvent(config) {\n var code = config.code;\n var reason = config.reason;\n var type = config.type;\n var target = config.target;\n var wasClean = config.wasClean;\n\n if (!wasClean) {\n wasClean = code === CLOSE_CODES.CLOSE_NORMAL || code === CLOSE_CODES.CLOSE_NO_STATUS;\n }\n\n var closeEvent = new CloseEvent(type, {\n code: code,\n reason: reason,\n wasClean: wasClean\n });\n\n if (target) {\n closeEvent.target = target;\n closeEvent.srcElement = target;\n closeEvent.currentTarget = target;\n }\n\n return closeEvent;\n}\n\nfunction closeWebSocketConnection(context, code, reason) {\n context.readyState = WebSocket$1.CLOSING;\n\n var server = networkBridge.serverLookup(context.url);\n var closeEvent = createCloseEvent({\n type: 'close',\n target: context.target,\n code: code,\n reason: reason\n });\n\n delay(function () {\n networkBridge.removeWebSocket(context, context.url);\n\n context.readyState = WebSocket$1.CLOSED;\n context.dispatchEvent(closeEvent);\n\n if (server) {\n server.dispatchEvent(closeEvent, server);\n }\n }, context);\n}\n\nfunction failWebSocketConnection(context, code, reason) {\n context.readyState = WebSocket$1.CLOSING;\n\n var server = networkBridge.serverLookup(context.url);\n var closeEvent = createCloseEvent({\n type: 'close',\n target: context.target,\n code: code,\n reason: reason,\n wasClean: false\n });\n\n var errorEvent = createEvent({\n type: 'error',\n target: context.target\n });\n\n delay(function () {\n networkBridge.removeWebSocket(context, context.url);\n\n context.readyState = WebSocket$1.CLOSED;\n context.dispatchEvent(errorEvent);\n context.dispatchEvent(closeEvent);\n\n if (server) {\n server.dispatchEvent(closeEvent, server);\n }\n }, context);\n}\n\nfunction normalizeSendData(data) {\n if (Object.prototype.toString.call(data) !== '[object Blob]' && !(data instanceof ArrayBuffer)) {\n data = String(data);\n }\n\n return data;\n}\n\nvar proxies = new WeakMap();\n\nfunction proxyFactory(target) {\n if (proxies.has(target)) {\n return proxies.get(target);\n }\n\n var proxy = new Proxy(target, {\n get: function get(obj, prop) {\n if (prop === 'close') {\n return function close(options) {\n if ( options === void 0 ) options = {};\n\n var code = options.code || CLOSE_CODES.CLOSE_NORMAL;\n var reason = options.reason || '';\n\n closeWebSocketConnection(proxy, code, reason);\n };\n }\n\n if (prop === 'send') {\n return function send(data) {\n data = normalizeSendData(data);\n\n target.dispatchEvent(\n createMessageEvent({\n type: 'message',\n data: data,\n origin: this.url,\n target: target\n })\n );\n };\n }\n\n var toSocketName = function (type) { return (type === 'message' ? (\"server::\" + type) : type); };\n if (prop === 'on') {\n return function onWrapper(type, cb) {\n target.addEventListener(toSocketName(type), cb);\n };\n }\n if (prop === 'off') {\n return function offWrapper(type, cb) {\n target.removeEventListener(toSocketName(type), cb);\n };\n }\n\n if (prop === 'target') {\n return target;\n }\n\n return obj[prop];\n }\n });\n proxies.set(target, proxy);\n\n return proxy;\n}\n\nfunction lengthInUtf8Bytes(str) {\n // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.\n var m = encodeURIComponent(str).match(/%[89ABab]/g);\n return str.length + (m ? m.length : 0);\n}\n\nfunction urlVerification(url) {\n var urlRecord = new urlParse(url);\n var pathname = urlRecord.pathname;\n var protocol = urlRecord.protocol;\n var hash = urlRecord.hash;\n\n if (!url) {\n throw new TypeError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" 1 argument required, but only 0 present.\"));\n }\n\n if (!pathname) {\n urlRecord.pathname = '/';\n }\n\n if (protocol === '') {\n throw new SyntaxError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The URL '\" + (urlRecord.toString()) + \"' is invalid.\"));\n }\n\n if (protocol !== 'ws:' && protocol !== 'wss:') {\n throw new SyntaxError(\n ((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The URL's scheme must be either 'ws' or 'wss'. '\" + protocol + \"' is not allowed.\")\n );\n }\n\n if (hash !== '') {\n /* eslint-disable max-len */\n throw new SyntaxError(\n ((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The URL contains a fragment identifier ('\" + hash + \"'). Fragment identifiers are not allowed in WebSocket URLs.\")\n );\n /* eslint-enable max-len */\n }\n\n return urlRecord.toString();\n}\n\nfunction protocolVerification(protocols) {\n if ( protocols === void 0 ) protocols = [];\n\n if (!Array.isArray(protocols) && typeof protocols !== 'string') {\n throw new SyntaxError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The subprotocol '\" + (protocols.toString()) + \"' is invalid.\"));\n }\n\n if (typeof protocols === 'string') {\n protocols = [protocols];\n }\n\n var uniq = protocols\n .map(function (p) { return ({ count: 1, protocol: p }); })\n .reduce(function (a, b) {\n a[b.protocol] = (a[b.protocol] || 0) + b.count;\n return a;\n }, {});\n\n var duplicates = Object.keys(uniq).filter(function (a) { return uniq[a] > 1; });\n\n if (duplicates.length > 0) {\n throw new SyntaxError(((ERROR_PREFIX.CONSTRUCTOR_ERROR) + \" The subprotocol '\" + (duplicates[0]) + \"' is duplicated.\"));\n }\n\n return protocols;\n}\n\n/*\n * The main websocket class which is designed to mimick the native WebSocket class as close\n * as possible.\n *\n * https://html.spec.whatwg.org/multipage/web-sockets.html\n */\nvar WebSocket$1 = (function (EventTarget$$1) {\n function WebSocket(url, protocols) {\n EventTarget$$1.call(this);\n\n this._onopen = null;\n this._onmessage = null;\n this._onerror = null;\n this._onclose = null;\n\n this.url = urlVerification(url);\n protocols = protocolVerification(protocols);\n this.protocol = protocols[0] || '';\n\n this.binaryType = 'blob';\n this.readyState = WebSocket.CONNECTING;\n\n var client = proxyFactory(this);\n var server = networkBridge.attachWebSocket(client, this.url);\n\n /*\n * This delay is needed so that we dont trigger an event before the callbacks have been\n * setup. For example:\n *\n * var socket = new WebSocket('ws://localhost');\n *\n * If we dont have the delay then the event would be triggered right here and this is\n * before the onopen had a chance to register itself.\n *\n * socket.onopen = () => { // this would never be called };\n *\n * and with the delay the event gets triggered here after all of the callbacks have been\n * registered :-)\n */\n delay(function delayCallback() {\n if (server) {\n if (\n server.options.verifyClient &&\n typeof server.options.verifyClient === 'function' &&\n !server.options.verifyClient()\n ) {\n this.readyState = WebSocket.CLOSED;\n\n log(\n 'error',\n (\"WebSocket connection to '\" + (this.url) + \"' failed: HTTP Authentication failed; no valid credentials available\")\n );\n\n networkBridge.removeWebSocket(client, this.url);\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(createCloseEvent({ type: 'close', target: this, code: CLOSE_CODES.CLOSE_NORMAL }));\n } else {\n if (server.options.selectProtocol && typeof server.options.selectProtocol === 'function') {\n var selectedProtocol = server.options.selectProtocol(protocols);\n var isFilled = selectedProtocol !== '';\n var isRequested = protocols.indexOf(selectedProtocol) !== -1;\n if (isFilled && !isRequested) {\n this.readyState = WebSocket.CLOSED;\n\n log('error', (\"WebSocket connection to '\" + (this.url) + \"' failed: Invalid Sub-Protocol\"));\n\n networkBridge.removeWebSocket(client, this.url);\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(createCloseEvent({ type: 'close', target: this, code: CLOSE_CODES.CLOSE_NORMAL }));\n return;\n }\n this.protocol = selectedProtocol;\n }\n this.readyState = WebSocket.OPEN;\n this.dispatchEvent(createEvent({ type: 'open', target: this }));\n server.dispatchEvent(createEvent({ type: 'connection' }), client);\n }\n } else {\n this.readyState = WebSocket.CLOSED;\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(createCloseEvent({ type: 'close', target: this, code: CLOSE_CODES.CLOSE_NORMAL }));\n\n log('error', (\"WebSocket connection to '\" + (this.url) + \"' failed\"));\n }\n }, this);\n }\n\n if ( EventTarget$$1 ) WebSocket.__proto__ = EventTarget$$1;\n WebSocket.prototype = Object.create( EventTarget$$1 && EventTarget$$1.prototype );\n WebSocket.prototype.constructor = WebSocket;\n\n var prototypeAccessors = { onopen: {},onmessage: {},onclose: {},onerror: {} };\n\n prototypeAccessors.onopen.get = function () {\n return this._onopen;\n };\n\n prototypeAccessors.onmessage.get = function () {\n return this._onmessage;\n };\n\n prototypeAccessors.onclose.get = function () {\n return this._onclose;\n };\n\n prototypeAccessors.onerror.get = function () {\n return this._onerror;\n };\n\n prototypeAccessors.onopen.set = function (listener) {\n this.removeEventListener('open', this._onopen);\n this._onopen = listener;\n this.addEventListener('open', listener);\n };\n\n prototypeAccessors.onmessage.set = function (listener) {\n this.removeEventListener('message', this._onmessage);\n this._onmessage = listener;\n this.addEventListener('message', listener);\n };\n\n prototypeAccessors.onclose.set = function (listener) {\n this.removeEventListener('close', this._onclose);\n this._onclose = listener;\n this.addEventListener('close', listener);\n };\n\n prototypeAccessors.onerror.set = function (listener) {\n this.removeEventListener('error', this._onerror);\n this._onerror = listener;\n this.addEventListener('error', listener);\n };\n\n WebSocket.prototype.send = function send (data) {\n var this$1 = this;\n\n if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) {\n throw new Error('WebSocket is already in CLOSING or CLOSED state');\n }\n\n // TODO: handle bufferedAmount\n\n var messageEvent = createMessageEvent({\n type: 'server::message',\n origin: this.url,\n data: normalizeSendData(data)\n });\n\n var server = networkBridge.serverLookup(this.url);\n\n if (server) {\n delay(function () {\n this$1.dispatchEvent(messageEvent, data);\n }, server);\n }\n };\n\n WebSocket.prototype.close = function close (code, reason) {\n if (code !== undefined) {\n if (typeof code !== 'number' || (code !== 1000 && (code < 3000 || code > 4999))) {\n throw new TypeError(\n ((ERROR_PREFIX.CLOSE_ERROR) + \" The code must be either 1000, or between 3000 and 4999. \" + code + \" is neither.\")\n );\n }\n }\n\n if (reason !== undefined) {\n var length = lengthInUtf8Bytes(reason);\n\n if (length > 123) {\n throw new SyntaxError(((ERROR_PREFIX.CLOSE_ERROR) + \" The message must not be greater than 123 bytes.\"));\n }\n }\n\n if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) {\n return;\n }\n\n var client = proxyFactory(this);\n if (this.readyState === WebSocket.CONNECTING) {\n failWebSocketConnection(client, code || CLOSE_CODES.CLOSE_ABNORMAL, reason);\n } else {\n closeWebSocketConnection(client, code || CLOSE_CODES.CLOSE_NO_STATUS, reason);\n }\n };\n\n Object.defineProperties( WebSocket.prototype, prototypeAccessors );\n\n return WebSocket;\n}(EventTarget));\n\nWebSocket$1.CONNECTING = 0;\nWebSocket$1.prototype.CONNECTING = WebSocket$1.CONNECTING;\nWebSocket$1.OPEN = 1;\nWebSocket$1.prototype.OPEN = WebSocket$1.OPEN;\nWebSocket$1.CLOSING = 2;\nWebSocket$1.prototype.CLOSING = WebSocket$1.CLOSING;\nWebSocket$1.CLOSED = 3;\nWebSocket$1.prototype.CLOSED = WebSocket$1.CLOSED;\n\n/*\n * The socket-io class is designed to mimick the real API as closely as possible.\n *\n * http://socket.io/docs/\n */\nvar SocketIO$1 = (function (EventTarget$$1) {\n function SocketIO(url, protocol) {\n var this$1 = this;\n if ( url === void 0 ) url = 'socket.io';\n if ( protocol === void 0 ) protocol = '';\n\n EventTarget$$1.call(this);\n\n this.binaryType = 'blob';\n var urlRecord = new urlParse(url);\n\n if (!urlRecord.pathname) {\n urlRecord.pathname = '/';\n }\n\n this.url = urlRecord.toString();\n this.readyState = SocketIO.CONNECTING;\n this.protocol = '';\n this.target = this;\n\n if (typeof protocol === 'string' || (typeof protocol === 'object' && protocol !== null)) {\n this.protocol = protocol;\n } else if (Array.isArray(protocol) && protocol.length > 0) {\n this.protocol = protocol[0];\n }\n\n var server = networkBridge.attachWebSocket(this, this.url);\n\n /*\n * Delay triggering the connection events so they can be defined in time.\n */\n delay(function delayCallback() {\n if (server) {\n this.readyState = SocketIO.OPEN;\n server.dispatchEvent(createEvent({ type: 'connection' }), server, this);\n server.dispatchEvent(createEvent({ type: 'connect' }), server, this); // alias\n this.dispatchEvent(createEvent({ type: 'connect', target: this }));\n } else {\n this.readyState = SocketIO.CLOSED;\n this.dispatchEvent(createEvent({ type: 'error', target: this }));\n this.dispatchEvent(\n createCloseEvent({\n type: 'close',\n target: this,\n code: CLOSE_CODES.CLOSE_NORMAL\n })\n );\n\n log('error', (\"Socket.io connection to '\" + (this.url) + \"' failed\"));\n }\n }, this);\n\n /**\n Add an aliased event listener for close / disconnect\n */\n this.addEventListener('close', function (event) {\n this$1.dispatchEvent(\n createCloseEvent({\n type: 'disconnect',\n target: event.target,\n code: event.code\n })\n );\n });\n }\n\n if ( EventTarget$$1 ) SocketIO.__proto__ = EventTarget$$1;\n SocketIO.prototype = Object.create( EventTarget$$1 && EventTarget$$1.prototype );\n SocketIO.prototype.constructor = SocketIO;\n\n var prototypeAccessors = { broadcast: {} };\n\n /*\n * Closes the SocketIO connection or connection attempt, if any.\n * If the connection is already CLOSED, this method does nothing.\n */\n SocketIO.prototype.close = function close () {\n if (this.readyState !== SocketIO.OPEN) {\n return undefined;\n }\n\n var server = networkBridge.serverLookup(this.url);\n networkBridge.removeWebSocket(this, this.url);\n\n this.readyState = SocketIO.CLOSED;\n this.dispatchEvent(\n createCloseEvent({\n type: 'close',\n target: this,\n code: CLOSE_CODES.CLOSE_NORMAL\n })\n );\n\n if (server) {\n server.dispatchEvent(\n createCloseEvent({\n type: 'disconnect',\n target: this,\n code: CLOSE_CODES.CLOSE_NORMAL\n }),\n server\n );\n }\n\n return this;\n };\n\n /*\n * Alias for Socket#close\n *\n * https://github.com/socketio/socket.io-client/blob/master/lib/socket.js#L383\n */\n SocketIO.prototype.disconnect = function disconnect () {\n return this.close();\n };\n\n /*\n * Submits an event to the server with a payload\n */\n SocketIO.prototype.emit = function emit (event) {\n var data = [], len = arguments.length - 1;\n while ( len-- > 0 ) data[ len ] = arguments[ len + 1 ];\n\n if (this.readyState !== SocketIO.OPEN) {\n throw new Error('SocketIO is already in CLOSING or CLOSED state');\n }\n\n var messageEvent = createMessageEvent({\n type: event,\n origin: this.url,\n data: data\n });\n\n var server = networkBridge.serverLookup(this.url);\n\n if (server) {\n server.dispatchEvent.apply(server, [ messageEvent ].concat( data ));\n }\n\n return this;\n };\n\n /*\n * Submits a 'message' event to the server.\n *\n * Should behave exactly like WebSocket#send\n *\n * https://github.com/socketio/socket.io-client/blob/master/lib/socket.js#L113\n */\n SocketIO.prototype.send = function send (data) {\n this.emit('message', data);\n return this;\n };\n\n /*\n * For broadcasting events to other connected sockets.\n *\n * e.g. socket.broadcast.emit('hi!');\n * e.g. socket.broadcast.to('my-room').emit('hi!');\n */\n prototypeAccessors.broadcast.get = function () {\n if (this.readyState !== SocketIO.OPEN) {\n throw new Error('SocketIO is already in CLOSING or CLOSED state');\n }\n\n var self = this;\n var server = networkBridge.serverLookup(this.url);\n if (!server) {\n throw new Error((\"SocketIO can not find a server at the specified URL (\" + (this.url) + \")\"));\n }\n\n return {\n emit: function emit(event, data) {\n server.emit(event, data, { websockets: networkBridge.websocketsLookup(self.url, null, self) });\n return self;\n },\n to: function to(room) {\n return server.to(room, self);\n },\n in: function in$1(room) {\n return server.in(room, self);\n }\n };\n };\n\n /*\n * For registering events to be received from the server\n */\n SocketIO.prototype.on = function on (type, callback) {\n this.addEventListener(type, callback);\n return this;\n };\n\n /*\n * Remove event listener\n *\n * https://github.com/component/emitter#emitteroffevent-fn\n */\n SocketIO.prototype.off = function off (type, callback) {\n this.removeEventListener(type, callback);\n };\n\n /*\n * Check if listeners have already been added for an event\n *\n * https://github.com/component/emitter#emitterhaslistenersevent\n */\n SocketIO.prototype.hasListeners = function hasListeners (type) {\n var listeners = this.listeners[type];\n if (!Array.isArray(listeners)) {\n return false;\n }\n return !!listeners.length;\n };\n\n /*\n * Join a room on a server\n *\n * http://socket.io/docs/rooms-and-namespaces/#joining-and-leaving\n */\n SocketIO.prototype.join = function join (room) {\n networkBridge.addMembershipToRoom(this, room);\n };\n\n /*\n * Get the websocket to leave the room\n *\n * http://socket.io/docs/rooms-and-namespaces/#joining-and-leaving\n */\n SocketIO.prototype.leave = function leave (room) {\n networkBridge.removeMembershipFromRoom(this, room);\n };\n\n SocketIO.prototype.to = function to (room) {\n return this.broadcast.to(room);\n };\n\n SocketIO.prototype.in = function in$1 () {\n return this.to.apply(null, arguments);\n };\n\n /*\n * Invokes all listener functions that are listening to the given event.type property. Each\n * listener will be passed the event as the first argument.\n *\n * @param {object} event - event object which will be passed to all listeners of the event.type property\n */\n SocketIO.prototype.dispatchEvent = function dispatchEvent (event) {\n var this$1 = this;\n var customArguments = [], len = arguments.length - 1;\n while ( len-- > 0 ) customArguments[ len ] = arguments[ len + 1 ];\n\n var eventName = event.type;\n var listeners = this.listeners[eventName];\n\n if (!Array.isArray(listeners)) {\n return false;\n }\n\n listeners.forEach(function (listener) {\n if (customArguments.length > 0) {\n listener.apply(this$1, customArguments);\n } else {\n // Regular WebSockets expect a MessageEvent but Socketio.io just wants raw data\n // payload instanceof MessageEvent works, but you can't isntance of NodeEvent\n // for now we detect if the output has data defined on it\n listener.call(this$1, event.data ? event.data : event);\n }\n });\n };\n\n Object.defineProperties( SocketIO.prototype, prototypeAccessors );\n\n return SocketIO;\n}(EventTarget));\n\nSocketIO$1.CONNECTING = 0;\nSocketIO$1.OPEN = 1;\nSocketIO$1.CLOSING = 2;\nSocketIO$1.CLOSED = 3;\n\n/*\n * Static constructor methods for the IO Socket\n */\nvar IO = function ioConstructor(url, protocol) {\n return new SocketIO$1(url, protocol);\n};\n\n/*\n * Alias the raw IO() constructor\n */\nIO.connect = function ioConnect(url, protocol) {\n /* eslint-disable new-cap */\n return IO(url, protocol);\n /* eslint-enable new-cap */\n};\n\nvar dedupe = function (arr) { return arr.reduce(function (deduped, b) {\n if (deduped.indexOf(b) > -1) { return deduped; }\n return deduped.concat(b);\n }, []); };\n\nfunction retrieveGlobalObject() {\n if (typeof window !== 'undefined') {\n return window;\n }\n\n return typeof process === 'object' && typeof require === 'function' && typeof global === 'object' ? global : this;\n}\n\nvar defaultOptions = {\n mock: true,\n verifyClient: null,\n selectProtocol: null\n};\n\nvar Server$1 = (function (EventTarget$$1) {\n function Server(url, options) {\n if ( options === void 0 ) options = defaultOptions;\n\n EventTarget$$1.call(this);\n var urlRecord = new urlParse(url);\n\n if (!urlRecord.pathname) {\n urlRecord.pathname = '/';\n }\n\n this.url = urlRecord.toString();\n\n this.originalWebSocket = null;\n var server = networkBridge.attachServer(this, this.url);\n\n if (!server) {\n this.dispatchEvent(createEvent({ type: 'error' }));\n throw new Error('A mock server is already listening on this url');\n }\n\n this.options = Object.assign({}, defaultOptions, options);\n\n if (this.options.mock) {\n this.mockWebsocket();\n }\n }\n\n if ( EventTarget$$1 ) Server.__proto__ = EventTarget$$1;\n Server.prototype = Object.create( EventTarget$$1 && EventTarget$$1.prototype );\n Server.prototype.constructor = Server;\n\n /*\n * Attaches the mock websocket object to the global object\n */\n Server.prototype.mockWebsocket = function mockWebsocket () {\n var globalObj = retrieveGlobalObject();\n\n this.originalWebSocket = globalObj.WebSocket;\n globalObj.WebSocket = WebSocket$1;\n };\n\n /*\n * Removes the mock websocket object from the global object\n */\n Server.prototype.restoreWebsocket = function restoreWebsocket () {\n var globalObj = retrieveGlobalObject();\n\n if (this.originalWebSocket !== null) {\n globalObj.WebSocket = this.originalWebSocket;\n }\n\n this.originalWebSocket = null;\n };\n\n /**\n * Removes itself from the urlMap so another server could add itself to the url.\n * @param {function} callback - The callback is called when the server is stopped\n */\n Server.prototype.stop = function stop (callback) {\n if ( callback === void 0 ) callback = function () {};\n\n if (this.options.mock) {\n this.restoreWebsocket();\n }\n\n networkBridge.removeServer(this.url);\n\n if (typeof callback === 'function') {\n callback();\n }\n };\n\n /*\n * This is the main function for the mock server to subscribe to the on events.\n *\n * ie: mockServer.on('connection', function() { console.log('a mock client connected'); });\n *\n * @param {string} type - The event key to subscribe to. Valid keys are: connection, message, and close.\n * @param {function} callback - The callback which should be called when a certain event is fired.\n */\n Server.prototype.on = function on (type, callback) {\n this.addEventListener(type, callback);\n };\n\n /*\n * Remove event listener\n */\n Server.prototype.off = function off (type, callback) {\n this.removeEventListener(type, callback);\n };\n\n /*\n * Closes the connection and triggers the onclose method of all listening\n * websockets. After that it removes itself from the urlMap so another server\n * could add itself to the url.\n *\n * @param {object} options\n */\n Server.prototype.close = function close (options) {\n if ( options === void 0 ) options = {};\n\n var code = options.code;\n var reason = options.reason;\n var wasClean = options.wasClean;\n var listeners = networkBridge.websocketsLookup(this.url);\n\n // Remove server before notifications to prevent immediate reconnects from\n // socket onclose handlers\n networkBridge.removeServer(this.url);\n\n listeners.forEach(function (socket) {\n socket.readyState = WebSocket$1.CLOSED;\n socket.dispatchEvent(\n createCloseEvent({\n type: 'close',\n target: socket.target,\n code: code || CLOSE_CODES.CLOSE_NORMAL,\n reason: reason || '',\n wasClean: wasClean\n })\n );\n });\n\n this.dispatchEvent(createCloseEvent({ type: 'close' }), this);\n };\n\n /*\n * Sends a generic message event to all mock clients.\n */\n Server.prototype.emit = function emit (event, data, options) {\n var this$1 = this;\n if ( options === void 0 ) options = {};\n\n var websockets = options.websockets;\n\n if (!websockets) {\n websockets = networkBridge.websocketsLookup(this.url);\n }\n\n var normalizedData;\n if (typeof options !== 'object' || arguments.length > 3) {\n data = Array.prototype.slice.call(arguments, 1, arguments.length);\n normalizedData = data.map(function (item) { return normalizeSendData(item); });\n } else {\n normalizedData = normalizeSendData(data);\n }\n\n websockets.forEach(function (socket) {\n var messageData = socket instanceof SocketIO$1 ? data : normalizedData;\n if (Array.isArray(messageData)) {\n socket.dispatchEvent.apply(\n socket, [ createMessageEvent({\n type: event,\n data: messageData,\n origin: this$1.url,\n target: socket.target\n }) ].concat( messageData )\n );\n } else {\n socket.dispatchEvent(\n createMessageEvent({\n type: event,\n data: messageData,\n origin: this$1.url,\n target: socket.target\n })\n );\n }\n });\n };\n\n /*\n * Returns an array of websockets which are listening to this server\n * TOOD: this should return a set and not be a method\n */\n Server.prototype.clients = function clients () {\n return networkBridge.websocketsLookup(this.url);\n };\n\n /*\n * Prepares a method to submit an event to members of the room\n *\n * e.g. server.to('my-room').emit('hi!');\n */\n Server.prototype.to = function to (room, broadcaster, broadcastList) {\n var this$1 = this;\n if ( broadcastList === void 0 ) broadcastList = [];\n\n var self = this;\n var websockets = dedupe(broadcastList.concat(networkBridge.websocketsLookup(this.url, room, broadcaster)));\n\n return {\n to: function (chainedRoom, chainedBroadcaster) { return this$1.to.call(this$1, chainedRoom, chainedBroadcaster, websockets); },\n emit: function emit(event, data) {\n self.emit(event, data, { websockets: websockets });\n }\n };\n };\n\n /*\n * Alias for Server.to\n */\n Server.prototype.in = function in$1 () {\n var args = [], len = arguments.length;\n while ( len-- ) args[ len ] = arguments[ len ];\n\n return this.to.apply(null, args);\n };\n\n /*\n * Simulate an event from the server to the clients. Useful for\n * simulating errors.\n */\n Server.prototype.simulate = function simulate (event) {\n var listeners = networkBridge.websocketsLookup(this.url);\n\n if (event === 'error') {\n listeners.forEach(function (socket) {\n socket.readyState = WebSocket$1.CLOSED;\n socket.dispatchEvent(createEvent({ type: 'error', target: socket.target }));\n });\n }\n };\n\n return Server;\n}(EventTarget));\n\n/*\n * Alternative constructor to support namespaces in socket.io\n *\n * http://socket.io/docs/rooms-and-namespaces/#custom-namespaces\n */\nServer$1.of = function of(url) {\n return new Server$1(url);\n};\n\nvar Server = Server$1;\nvar WebSocket = WebSocket$1;\nvar SocketIO$$1 = IO;\n\nexports.Server = Server;\nexports.WebSocket = WebSocket;\nexports.SocketIO = SocketIO$$1;\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n})));\n","// 'path' module extracted from Node.js v8.11.1 (only the posix part)\n// transplited with Babel\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));\n }\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n var res = '';\n var lastSegmentLength = 0;\n var lastSlash = -1;\n var dots = 0;\n var code;\n for (var i = 0; i <= path.length; ++i) {\n if (i < path.length)\n code = path.charCodeAt(i);\n else if (code === 47 /*/*/)\n break;\n else\n code = 47 /*/*/;\n if (code === 47 /*/*/) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n if (res.length > 2) {\n var lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0)\n res += '/..';\n else\n res = '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction _format(sep, pathObject) {\n var dir = pathObject.dir || pathObject.root;\n var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n if (!dir) {\n return base;\n }\n if (dir === pathObject.root) {\n return dir + base;\n }\n return dir + sep + base;\n}\n\nvar posix = {\n // path.resolve([from ...], to)\n resolve: function resolve() {\n var resolvedPath = '';\n var resolvedAbsolute = false;\n var cwd;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path;\n if (i >= 0)\n path = arguments[i];\n else {\n if (cwd === undefined)\n cwd = process.cwd();\n path = cwd;\n }\n\n assertPath(path);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0)\n return '/' + resolvedPath;\n else\n return '/';\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n } else {\n return '.';\n }\n },\n\n normalize: function normalize(path) {\n assertPath(path);\n\n if (path.length === 0) return '.';\n\n var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute);\n\n if (path.length === 0 && !isAbsolute) path = '.';\n if (path.length > 0 && trailingSeparator) path += '/';\n\n if (isAbsolute) return '/' + path;\n return path;\n },\n\n isAbsolute: function isAbsolute(path) {\n assertPath(path);\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n },\n\n join: function join() {\n if (arguments.length === 0)\n return '.';\n var joined;\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n assertPath(arg);\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += '/' + arg;\n }\n }\n if (joined === undefined)\n return '.';\n return posix.normalize(joined);\n },\n\n relative: function relative(from, to) {\n assertPath(from);\n assertPath(to);\n\n if (from === to) return '';\n\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to) return '';\n\n // Trim any leading backslashes\n var fromStart = 1;\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/)\n break;\n }\n var fromEnd = from.length;\n var fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n var toStart = 1;\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/)\n break;\n }\n var toEnd = to.length;\n var toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n var length = fromLen < toLen ? fromLen : toLen;\n var lastCommonSep = -1;\n var i = 0;\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0;\n }\n }\n break;\n }\n var fromCode = from.charCodeAt(fromStart + i);\n var toCode = to.charCodeAt(toStart + i);\n if (fromCode !== toCode)\n break;\n else if (fromCode === 47 /*/*/)\n lastCommonSep = i;\n }\n\n var out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0)\n out += '..';\n else\n out += '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return out + to.slice(toStart + lastCommonSep);\n else {\n toStart += lastCommonSep;\n if (to.charCodeAt(toStart) === 47 /*/*/)\n ++toStart;\n return to.slice(toStart);\n }\n },\n\n _makeLong: function _makeLong(path) {\n return path;\n },\n\n dirname: function dirname(path) {\n assertPath(path);\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) return '//';\n return path.slice(0, end);\n },\n\n basename: function basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n assertPath(path);\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return '';\n var extIdx = ext.length - 1;\n var firstNonSlashEnd = -1;\n for (i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n return path.slice(start, end);\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n }\n },\n\n extname: function extname(path) {\n assertPath(path);\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n }\n return _format('/', pathObject);\n },\n\n parse: function parse(path) {\n assertPath(path);\n\n var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0) return ret;\n var code = path.charCodeAt(0);\n var isAbsolute = code === 47 /*/*/;\n var start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n var i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot);\n ret.base = path.slice(1, end);\n } else {\n ret.name = path.slice(startPart, startDot);\n ret.base = path.slice(startPart, end);\n }\n ret.ext = path.slice(startDot, end);\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n return ret;\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n","'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n","import { startJupyterLiteServer } from './jlite';\nimport type { ThebeLiteGlobal } from './types';\n\ndeclare global {\n interface Window {\n thebeLite?: ThebeLiteGlobal;\n }\n}\n\nfunction setupThebeLite() {\n window.thebeLite = Object.assign(window.thebeLite ?? {}, { startJupyterLiteServer });\n}\n\nif (typeof window !== 'undefined') {\n console.debug('window is defined, setting up thebe-lite');\n setupThebeLite();\n console.debug('window.thebeLite', window.thebeLite);\n}\n\nexport * from './types';\nexport { startJupyterLiteServer, setupThebeLite };\n","import type { ServiceManager } from '@jupyterlab/services';\nimport type { LiteServerConfig } from './types';\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport { JupyterLiteServer } from '@jupyterlite/server';\n\nconst serverExtensions = [import('@jupyterlite/server-extension')];\n\nasync function createModule(scope: string, module: string) {\n try {\n const factory = await (window as any)._JUPYTERLAB[scope].get(module);\n return factory();\n } catch (e) {\n console.warn(`Failed to create module: package: ${scope}; module: ${module}`);\n throw e;\n }\n}\n\n/**\n * Iterate over active plugins in an extension.\n */\nfunction* activePlugins(extension: any) {\n // Handle commonjs or es2015 modules\n let exports;\n if (Object.prototype.hasOwnProperty.call(extension, '__esModule')) {\n exports = extension.default;\n } else {\n // CommonJS exports.\n exports = extension;\n }\n\n const plugins = Array.isArray(exports) ? exports : [exports];\n for (const plugin of plugins) {\n yield plugin;\n }\n}\n\nexport async function startJupyterLiteServer(config?: LiteServerConfig): Promise {\n /**\n * This is sufficent to initialise the global object?\n */\n PageConfig.getOption('');\n\n /**\n * Do not rely on a configuration being on the document body, accept configuration via arguments\n * and set options on the page config directly\n */\n if (config?.litePluginSettings) {\n PageConfig.setOption('litePluginSettings', JSON.stringify(config.litePluginSettings));\n }\n\n /**\n * Seems like there are 4 different extensions we may want to handle\n *\n * liteExtension - essential, as these are how kernels are added\n * federatedExtension - general jupyterlab extensions\n * federatedMimeExtension - render extensions? e.g. @jupyterlab/javascript-extension, @jupyterlab/json-extension\n * federatedStyles - ?\n *\n * TODO we're not suppporting all of these yet\n */\n\n const litePluginsToRegister: JupyterLiteServer.IPluginModule[] = [];\n\n // Add the base serverlite extensions\n const baseServerExtensions = await Promise.all(serverExtensions);\n baseServerExtensions.forEach((p) => {\n for (const plugin of activePlugins(p)) {\n litePluginsToRegister.push(plugin);\n }\n });\n\n // TODO get federated extensions in from config argument?\n const extensions: any[] = [];\n\n const liteExtensionPromises: any[] = [import('@jupyterlite/pyodide-kernel-extension')];\n\n extensions.forEach((data) => {\n if (data.liteExtension) {\n liteExtensionPromises.push(createModule(data.name, data.extension));\n return;\n }\n });\n\n // Add the serverlite federated extensions.\n const federatedLiteExtensions = await Promise.allSettled(liteExtensionPromises);\n federatedLiteExtensions.forEach((p) => {\n if (p.status === 'fulfilled') {\n for (const plugin of activePlugins(p.value)) {\n litePluginsToRegister.push(plugin);\n }\n } else {\n console.error(p.reason);\n }\n });\n\n // create the in-browser JupyterLite Server\n const jupyterLiteServer = new JupyterLiteServer({} as any);\n jupyterLiteServer.registerPluginModules(litePluginsToRegister);\n // start the server\n await jupyterLiteServer.start();\n\n const { serviceManager } = jupyterLiteServer;\n await serviceManager.ready;\n\n // TODO\n return serviceManager as unknown as ServiceManager;\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ActivityMonitor = void 0;\nconst signaling_1 = require(\"@lumino/signaling\");\n/**\n * A class that monitors activity on a signal.\n */\nclass ActivityMonitor {\n /**\n * Construct a new activity monitor.\n */\n constructor(options) {\n this._timer = -1;\n this._timeout = -1;\n this._isDisposed = false;\n this._activityStopped = new signaling_1.Signal(this);\n options.signal.connect(this._onSignalFired, this);\n this._timeout = options.timeout || 1000;\n }\n /**\n * A signal emitted when activity has ceased.\n */\n get activityStopped() {\n return this._activityStopped;\n }\n /**\n * The timeout associated with the monitor, in milliseconds.\n */\n get timeout() {\n return this._timeout;\n }\n set timeout(value) {\n this._timeout = value;\n }\n /**\n * Test whether the monitor has been disposed.\n *\n * #### Notes\n * This is a read-only property.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources used by the activity monitor.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n signaling_1.Signal.clearData(this);\n }\n /**\n * A signal handler for the monitored signal.\n */\n _onSignalFired(sender, args) {\n clearTimeout(this._timer);\n this._sender = sender;\n this._args = args;\n this._timer = setTimeout(() => {\n this._activityStopped.emit({\n sender: this._sender,\n args: this._args\n });\n }, this._timeout);\n }\n}\nexports.ActivityMonitor = ActivityMonitor;\n//# sourceMappingURL=activitymonitor.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module coreutils\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./activitymonitor\"), exports);\n__exportStar(require(\"./interfaces\"), exports);\n__exportStar(require(\"./markdowncodeblocks\"), exports);\n__exportStar(require(\"./pageconfig\"), exports);\n__exportStar(require(\"./path\"), exports);\n__exportStar(require(\"./signal\"), exports);\n__exportStar(require(\"./text\"), exports);\n__exportStar(require(\"./time\"), exports);\n__exportStar(require(\"./url\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=interfaces.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MarkdownCodeBlocks = void 0;\n/**\n * The namespace for code block functions which help\n * in extract code from markdown text\n */\nvar MarkdownCodeBlocks;\n(function (MarkdownCodeBlocks) {\n MarkdownCodeBlocks.CODE_BLOCK_MARKER = '```';\n const markdownExtensions = [\n '.markdown',\n '.mdown',\n '.mkdn',\n '.md',\n '.mkd',\n '.mdwn',\n '.mdtxt',\n '.mdtext',\n '.text',\n '.txt',\n '.Rmd'\n ];\n class MarkdownCodeBlock {\n constructor(startLine) {\n this.startLine = startLine;\n this.code = '';\n this.endLine = -1;\n }\n }\n MarkdownCodeBlocks.MarkdownCodeBlock = MarkdownCodeBlock;\n /**\n * Check whether the given file extension is a markdown extension\n * @param extension - A file extension\n *\n * @returns true/false depending on whether this is a supported markdown extension\n */\n function isMarkdown(extension) {\n return markdownExtensions.indexOf(extension) > -1;\n }\n MarkdownCodeBlocks.isMarkdown = isMarkdown;\n /**\n * Construct all code snippets from current text\n * (this could be potentially optimized if we can cache and detect differences)\n * @param text - A string to parse codeblocks from\n *\n * @returns An array of MarkdownCodeBlocks.\n */\n function findMarkdownCodeBlocks(text) {\n if (!text || text === '') {\n return [];\n }\n const lines = text.split('\\n');\n const codeBlocks = [];\n let currentBlock = null;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n const lineContainsMarker = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER) === 0;\n const constructingBlock = currentBlock != null;\n // Skip this line if it is not part of any code block and doesn't contain a marker.\n if (!lineContainsMarker && !constructingBlock) {\n continue;\n }\n // Check if we are already constructing a code block.\n if (!constructingBlock) {\n // Start constructing a new code block.\n currentBlock = new MarkdownCodeBlock(lineIndex);\n // Check whether this is a single line code block of the form ```a = 10```.\n const firstIndex = line.indexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const lastIndex = line.lastIndexOf(MarkdownCodeBlocks.CODE_BLOCK_MARKER);\n const isSingleLine = firstIndex !== lastIndex;\n if (isSingleLine) {\n currentBlock.code = line.substring(firstIndex + MarkdownCodeBlocks.CODE_BLOCK_MARKER.length, lastIndex);\n currentBlock.endLine = lineIndex;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n }\n else if (currentBlock) {\n if (lineContainsMarker) {\n // End of block, finish it up.\n currentBlock.endLine = lineIndex - 1;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n else {\n // Append the current line.\n currentBlock.code += line + '\\n';\n }\n }\n }\n return codeBlocks;\n }\n MarkdownCodeBlocks.findMarkdownCodeBlocks = findMarkdownCodeBlocks;\n})(MarkdownCodeBlocks = exports.MarkdownCodeBlocks || (exports.MarkdownCodeBlocks = {}));\n//# sourceMappingURL=markdowncodeblocks.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PageConfig = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\nconst minimist_1 = __importDefault(require(\"minimist\"));\nconst url_1 = require(\"./url\");\n/**\n * The namespace for `PageConfig` functions.\n */\nvar PageConfig;\n(function (PageConfig) {\n /**\n * Get global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n *\n * @returns The config value or an empty string if not found.\n *\n * #### Notes\n * All values are treated as strings.\n * For browser based applications, it is assumed that the page HTML\n * includes a script tag with the id `jupyter-config-data` containing the\n * configuration as valid JSON. In order to support the classic Notebook,\n * we fall back on checking for `body` data of the given `name`.\n *\n * For node applications, it is assumed that the process was launched\n * with a `--jupyter-config-data` option pointing to a JSON settings\n * file.\n */\n function getOption(name) {\n if (configData) {\n return configData[name] || getBodyData(name);\n }\n configData = Object.create(null);\n let found = false;\n // Use script tag if available.\n if (typeof document !== 'undefined' && document) {\n const el = document.getElementById('jupyter-config-data');\n if (el) {\n configData = JSON.parse(el.textContent || '');\n found = true;\n }\n }\n // Otherwise use CLI if given.\n if (!found && typeof process !== 'undefined' && process.argv) {\n try {\n const cli = (0, minimist_1.default)(process.argv.slice(2));\n const path = require('path');\n let fullPath = '';\n if ('jupyter-config-data' in cli) {\n fullPath = path.resolve(cli['jupyter-config-data']);\n }\n else if ('JUPYTER_CONFIG_DATA' in process.env) {\n fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);\n }\n if (fullPath) {\n // Force Webpack to ignore this require.\n // eslint-disable-next-line\n configData = eval('require')(fullPath);\n }\n }\n catch (e) {\n console.error(e);\n }\n }\n if (!coreutils_1.JSONExt.isObject(configData)) {\n configData = Object.create(null);\n }\n else {\n for (const key in configData) {\n // PageConfig expects strings\n if (typeof configData[key] !== 'string') {\n configData[key] = JSON.stringify(configData[key]);\n }\n }\n }\n return configData[name] || getBodyData(name);\n }\n PageConfig.getOption = getOption;\n /**\n * Set global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n * @param value - The value to set the option to.\n *\n * @returns The last config value or an empty string if it doesn't exist.\n */\n function setOption(name, value) {\n const last = getOption(name);\n configData[name] = value;\n return last;\n }\n PageConfig.setOption = setOption;\n /**\n * Get the base url for a Jupyter application, or the base url of the page.\n */\n function getBaseUrl() {\n return url_1.URLExt.normalize(getOption('baseUrl') || '/');\n }\n PageConfig.getBaseUrl = getBaseUrl;\n /**\n * Get the tree url for a JupyterLab application.\n */\n function getTreeUrl() {\n return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }\n PageConfig.getTreeUrl = getTreeUrl;\n /**\n * Get the base url for sharing links (usually baseUrl)\n */\n function getShareUrl() {\n return url_1.URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }\n PageConfig.getShareUrl = getShareUrl;\n /**\n * Get the tree url for shareable links.\n * Usually the same as treeUrl,\n * but overrideable e.g. when sharing with JupyterHub.\n */\n function getTreeShareUrl() {\n return url_1.URLExt.normalize(url_1.URLExt.join(getShareUrl(), getOption('treeUrl')));\n }\n PageConfig.getTreeShareUrl = getTreeShareUrl;\n /**\n * Create a new URL given an optional mode and tree path.\n *\n * This is used to create URLS when the mode or tree path change as the user\n * changes mode or the current document in the main area. If fields in\n * options are omitted, the value in PageConfig will be used.\n *\n * @param options - IGetUrlOptions for the new path.\n */\n function getUrl(options) {\n var _a, _b, _c, _d;\n let path = options.toShare ? getShareUrl() : getBaseUrl();\n const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : getOption('mode');\n const workspace = (_b = options.workspace) !== null && _b !== void 0 ? _b : getOption('workspace');\n const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';\n path = url_1.URLExt.join(path, labOrDoc);\n if (workspace !== PageConfig.defaultWorkspace) {\n path = url_1.URLExt.join(path, 'workspaces', encodeURIComponent((_c = getOption('workspace')) !== null && _c !== void 0 ? _c : PageConfig.defaultWorkspace));\n }\n const treePath = (_d = options.treePath) !== null && _d !== void 0 ? _d : getOption('treePath');\n if (treePath) {\n path = url_1.URLExt.join(path, 'tree', url_1.URLExt.encodeParts(treePath));\n }\n return path;\n }\n PageConfig.getUrl = getUrl;\n PageConfig.defaultWorkspace = 'default';\n /**\n * Get the base websocket url for a Jupyter application, or an empty string.\n */\n function getWsUrl(baseUrl) {\n let wsUrl = getOption('wsUrl');\n if (!wsUrl) {\n baseUrl = baseUrl ? url_1.URLExt.normalize(baseUrl) : getBaseUrl();\n if (baseUrl.indexOf('http') !== 0) {\n return '';\n }\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n return url_1.URLExt.normalize(wsUrl);\n }\n PageConfig.getWsUrl = getWsUrl;\n /**\n * Returns the URL converting this notebook to a certain\n * format with nbconvert.\n */\n function getNBConvertURL({ path, format, download }) {\n const notebookPath = url_1.URLExt.encodeParts(path);\n const url = url_1.URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);\n if (download) {\n return url + '?download=true';\n }\n return url;\n }\n PageConfig.getNBConvertURL = getNBConvertURL;\n /**\n * Get the authorization token for a Jupyter application.\n */\n function getToken() {\n return getOption('token') || getBodyData('jupyterApiToken');\n }\n PageConfig.getToken = getToken;\n /**\n * Get the Notebook version info [major, minor, patch].\n */\n function getNotebookVersion() {\n const notebookVersion = getOption('notebookVersion');\n if (notebookVersion === '') {\n return [0, 0, 0];\n }\n return JSON.parse(notebookVersion);\n }\n PageConfig.getNotebookVersion = getNotebookVersion;\n /**\n * Private page config data for the Jupyter application.\n */\n let configData = null;\n /**\n * Get a url-encoded item from `body.data` and decode it\n * We should never have any encoded URLs anywhere else in code\n * until we are building an actual request.\n */\n function getBodyData(key) {\n if (typeof document === 'undefined' || !document.body) {\n return '';\n }\n const val = document.body.dataset[key];\n if (typeof val === 'undefined') {\n return '';\n }\n return decodeURIComponent(val);\n }\n /**\n * The namespace for page config `Extension` functions.\n */\n let Extension;\n (function (Extension) {\n /**\n * Populate an array from page config.\n *\n * @param key - The page config key (e.g., `deferredExtensions`).\n *\n * #### Notes\n * This is intended for `deferredExtensions` and `disabledExtensions`.\n */\n function populate(key) {\n try {\n const raw = getOption(key);\n if (raw) {\n return JSON.parse(raw);\n }\n }\n catch (error) {\n console.warn(`Unable to parse ${key}.`, error);\n }\n return [];\n }\n /**\n * The collection of deferred extensions in page config.\n */\n Extension.deferred = populate('deferredExtensions');\n /**\n * The collection of disabled extensions in page config.\n */\n Extension.disabled = populate('disabledExtensions');\n /**\n * Returns whether a plugin is deferred.\n *\n * @param id - The plugin ID.\n */\n function isDeferred(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.deferred.some(val => val === id || (extName && val === extName));\n }\n Extension.isDeferred = isDeferred;\n /**\n * Returns whether a plugin is disabled.\n *\n * @param id - The plugin ID.\n */\n function isDisabled(id) {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return Extension.disabled.some(val => val === id || (extName && val === extName));\n }\n Extension.isDisabled = isDisabled;\n })(Extension = PageConfig.Extension || (PageConfig.Extension = {}));\n})(PageConfig = exports.PageConfig || (exports.PageConfig = {}));\n//# sourceMappingURL=pageconfig.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PathExt = void 0;\nconst path_1 = require(\"path\");\n/**\n * The namespace for path-related functions.\n *\n * Note that Jupyter server paths do not start with a leading slash.\n */\nvar PathExt;\n(function (PathExt) {\n /**\n * Join all arguments together and normalize the resulting path.\n * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n *\n * @param paths - The string paths to join.\n */\n function join(...paths) {\n const path = path_1.posix.join(...paths);\n return path === '.' ? '' : removeSlash(path);\n }\n PathExt.join = join;\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * Often used to extract the file name from a fully qualified path.\n *\n * @param path - The path to evaluate.\n *\n * @param ext - An extension to remove from the result.\n */\n function basename(path, ext) {\n return path_1.posix.basename(path, ext);\n }\n PathExt.basename = basename;\n /**\n * Get the directory name of a path, similar to the Unix dirname command.\n * When an empty path is given, returns the root path.\n *\n * @param path - The file path.\n */\n function dirname(path) {\n const dir = removeSlash(path_1.posix.dirname(path));\n return dir === '.' ? '' : dir;\n }\n PathExt.dirname = dirname;\n /**\n * Get the extension of the path.\n *\n * @param path - The file path.\n *\n * @returns the extension of the file.\n *\n * #### Notes\n * The extension is the string from the last occurrence of the `.`\n * character to end of string in the last portion of the path, inclusive.\n * If there is no `.` in the last portion of the path, or if the first\n * character of the basename of path [[basename]] is `.`, then an\n * empty string is returned.\n */\n function extname(path) {\n return path_1.posix.extname(path);\n }\n PathExt.extname = extname;\n /**\n * Normalize a string path, reducing '..' and '.' parts.\n * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n * When an empty path is given, returns the root path.\n *\n * @param path - The string path to normalize.\n */\n function normalize(path) {\n if (path === '') {\n return '';\n }\n return removeSlash(path_1.posix.normalize(path));\n }\n PathExt.normalize = normalize;\n /**\n * Resolve a sequence of paths or path segments into an absolute path.\n * The root path in the application has no leading slash, so it is removed.\n *\n * @param parts - The paths to join.\n *\n * #### Notes\n * The right-most parameter is considered \\{to\\}. Other parameters are considered an array of \\{from\\}.\n *\n * Starting from leftmost \\{from\\} parameter, resolves \\{to\\} to an absolute path.\n *\n * If \\{to\\} isn't already absolute, \\{from\\} arguments are prepended in right to left order, until an absolute path is found. If after using all \\{from\\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n */\n function resolve(...parts) {\n return removeSlash(path_1.posix.resolve(...parts));\n }\n PathExt.resolve = resolve;\n /**\n * Solve the relative path from \\{from\\} to \\{to\\}.\n *\n * @param from - The source path.\n *\n * @param to - The target path.\n *\n * #### Notes\n * If from and to each resolve to the same path (after calling\n * path.resolve() on each), a zero-length string is returned.\n * If a zero-length string is passed as from or to, `/`\n * will be used instead of the zero-length strings.\n */\n function relative(from, to) {\n return removeSlash(path_1.posix.relative(from, to));\n }\n PathExt.relative = relative;\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * @param extension - the file extension.\n *\n * #### Notes\n * Adds a leading dot if not present and converts to lower case.\n */\n function normalizeExtension(extension) {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n PathExt.normalizeExtension = normalizeExtension;\n /**\n * Remove the leading slash from a path.\n *\n * @param path: the path from which to remove a leading slash.\n */\n function removeSlash(path) {\n if (path.indexOf('/') === 0) {\n path = path.slice(1);\n }\n return path;\n }\n PathExt.removeSlash = removeSlash;\n})(PathExt = exports.PathExt || (exports.PathExt = {}));\n//# sourceMappingURL=path.js.map","\"use strict\";\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.signalToPromise = void 0;\nconst coreutils_1 = require(\"@lumino/coreutils\");\n/**\n * Convert a signal into a promise for the first emitted value.\n *\n * @param signal - The signal we are listening to.\n * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)\n *\n * @returns a Promise that resolves with a `(sender, args)` pair.\n */\nfunction signalToPromise(signal, timeout) {\n const waitForSignal = new coreutils_1.PromiseDelegate();\n function cleanup() {\n signal.disconnect(slot);\n }\n function slot(sender, args) {\n cleanup();\n waitForSignal.resolve([sender, args]);\n }\n signal.connect(slot);\n if ((timeout !== null && timeout !== void 0 ? timeout : 0) > 0) {\n setTimeout(() => {\n cleanup();\n waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);\n }, timeout);\n }\n return waitForSignal.promise;\n}\nexports.signalToPromise = signalToPromise;\n//# sourceMappingURL=signal.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Text = void 0;\n/**\n * The namespace for text-related functions.\n */\nvar Text;\n(function (Text) {\n // javascript stores text as utf16 and string indices use \"code units\",\n // which stores high-codepoint characters as \"surrogate pairs\",\n // which occupy two indices in the javascript string.\n // We need to translate cursor_pos in the Jupyter protocol (in characters)\n // to js offset (with surrogate pairs taking two spots).\n const HAS_SURROGATES = '𝐚'.length > 1;\n /**\n * Convert a javascript string index into a unicode character offset\n *\n * @param jsIdx - The javascript string index (counting surrogate pairs)\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The unicode character offset\n */\n function jsIndexToCharIndex(jsIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return jsIdx;\n }\n let charIdx = jsIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n charIdx--;\n i++;\n }\n }\n }\n return charIdx;\n }\n Text.jsIndexToCharIndex = jsIndexToCharIndex;\n /**\n * Convert a unicode character offset to a javascript string index.\n *\n * @param charIdx - The index in unicode characters\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The js-native index\n */\n function charIndexToJsIndex(charIdx, text) {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return charIdx;\n }\n let jsIdx = charIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n jsIdx++;\n i++;\n }\n }\n }\n return jsIdx;\n }\n Text.charIndexToJsIndex = charIndexToJsIndex;\n /**\n * Given a 'snake-case', 'snake_case', 'snake:case', or\n * 'snake case' string, will return the camel case version: 'snakeCase'.\n *\n * @param str: the snake-case input string.\n *\n * @param upper: default = false. If true, the first letter of the\n * returned string will be capitalized.\n *\n * @returns the camel case version of the input string.\n */\n function camelCase(str, upper = false) {\n return str.replace(/^(\\w)|[\\s-_:]+(\\w)/g, function (match, p1, p2) {\n if (p2) {\n return p2.toUpperCase();\n }\n else {\n return upper ? p1.toUpperCase() : p1.toLowerCase();\n }\n });\n }\n Text.camelCase = camelCase;\n /**\n * Given a string, title case the words in the string.\n *\n * @param str: the string to title case.\n *\n * @returns the same string, but with each word capitalized.\n */\n function titleCase(str) {\n return (str || '')\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n Text.titleCase = titleCase;\n})(Text = exports.Text || (exports.Text = {}));\n//# sourceMappingURL=text.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Time = void 0;\n/**\n * A list of time units with their associated value in milliseconds.\n */\nconst UNITS = [\n { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },\n { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },\n { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },\n { name: 'hours', milliseconds: 60 * 60 * 1000 },\n { name: 'minutes', milliseconds: 60 * 1000 },\n { name: 'seconds', milliseconds: 1000 }\n];\n/**\n * The namespace for date functions.\n */\nvar Time;\n(function (Time) {\n /**\n * Convert a timestring to a human readable string (e.g. 'two minutes ago').\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function formatHuman(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.RelativeTimeFormat(lang, { numeric: 'auto' });\n const delta = new Date(value).getTime() - Date.now();\n for (let unit of UNITS) {\n const amount = Math.ceil(delta / unit.milliseconds);\n if (amount === 0) {\n continue;\n }\n return formatter.format(amount, unit.name);\n }\n return formatter.format(0, 'seconds');\n }\n Time.formatHuman = formatHuman;\n /**\n * Convenient helper to convert a timestring to a date format.\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n function format(value) {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.DateTimeFormat(lang, {\n dateStyle: 'short',\n timeStyle: 'short'\n });\n return formatter.format(new Date(value));\n }\n Time.format = format;\n})(Time = exports.Time || (exports.Time = {}));\n//# sourceMappingURL=time.js.map","\"use strict\";\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URLExt = void 0;\nconst path_1 = require(\"path\");\nconst url_parse_1 = __importDefault(require(\"url-parse\"));\n/**\n * The namespace for URL-related functions.\n */\nvar URLExt;\n(function (URLExt) {\n /**\n * Parse a url into a URL object.\n *\n * @param urlString - The URL string to parse.\n *\n * @returns A URL object.\n */\n function parse(url) {\n if (typeof document !== 'undefined' && document) {\n const a = document.createElement('a');\n a.href = url;\n return a;\n }\n return (0, url_parse_1.default)(url);\n }\n URLExt.parse = parse;\n /**\n * Parse URL and retrieve hostname\n *\n * @param url - The URL string to parse\n *\n * @returns a hostname string value\n */\n function getHostName(url) {\n return (0, url_parse_1.default)(url).hostname;\n }\n URLExt.getHostName = getHostName;\n function normalize(url) {\n return url && parse(url).toString();\n }\n URLExt.normalize = normalize;\n /**\n * Join a sequence of url components and normalizes as in node `path.join`.\n *\n * @param parts - The url components.\n *\n * @returns the joined url.\n */\n function join(...parts) {\n let u = (0, url_parse_1.default)(parts[0], {});\n // Schema-less URL can be only parsed as relative to a base URL\n // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326\n const isSchemaLess = u.protocol === '' && u.slashes;\n if (isSchemaLess) {\n u = (0, url_parse_1.default)(parts[0], 'https:' + parts[0]);\n }\n const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${u.auth}${u.auth ? '@' : ''}${u.host}`;\n // If there was a prefix, then the first path must start at the root.\n const path = path_1.posix.join(`${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`, ...parts.slice(1));\n return `${prefix}${path === '.' ? '' : path}`;\n }\n URLExt.join = join;\n /**\n * Encode the components of a multi-segment url.\n *\n * @param url - The url to encode.\n *\n * @returns the encoded url.\n *\n * #### Notes\n * Preserves the `'/'` separators.\n * Should not include the base url, since all parts are escaped.\n */\n function encodeParts(url) {\n return join(...url.split('/').map(encodeURIComponent));\n }\n URLExt.encodeParts = encodeParts;\n /**\n * Return a serialized object string suitable for a query.\n *\n * @param object - The source object.\n *\n * @returns an encoded url query.\n *\n * #### Notes\n * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).\n */\n function objectToQueryString(value) {\n const keys = Object.keys(value).filter(key => key.length > 0);\n if (!keys.length) {\n return '';\n }\n return ('?' +\n keys\n .map(key => {\n const content = encodeURIComponent(String(value[key]));\n return key + (content ? '=' + content : '');\n })\n .join('&'));\n }\n URLExt.objectToQueryString = objectToQueryString;\n /**\n * Return a parsed object that represents the values in a query string.\n */\n function queryStringToObject(value) {\n return value\n .replace(/^\\?/, '')\n .split('&')\n .reduce((acc, val) => {\n const [key, value] = val.split('=');\n if (key.length > 0) {\n acc[key] = decodeURIComponent(value || '');\n }\n return acc;\n }, {});\n }\n URLExt.queryStringToObject = queryStringToObject;\n /**\n * Test whether the url is a local url.\n *\n * #### Notes\n * This function returns `false` for any fully qualified url, including\n * `data:`, `file:`, and `//` protocol URLs.\n */\n function isLocal(url) {\n const { protocol } = parse(url);\n return ((!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&\n url.indexOf('/') !== 0);\n }\n URLExt.isLocal = isLocal;\n})(URLExt = exports.URLExt || (exports.URLExt = {}));\n//# sourceMappingURL=url.js.map","import { PageConfig } from '@jupyterlab/coreutils';\nimport mime from 'mime';\nimport { Token } from '@lumino/coreutils';\n/**\n * The token for the settings service.\n */\nexport const IContents = new Token('@jupyterlite/contents:IContents');\n/**\n * Commonly-used mimetypes\n */\nexport var MIME;\n(function (MIME) {\n MIME.JSON = 'application/json';\n MIME.PLAIN_TEXT = 'text/plain';\n MIME.OCTET_STREAM = 'octet/stream';\n})(MIME || (MIME = {}));\n/**\n * A namespace for file constructs.\n */\nexport var FILE;\n(function (FILE) {\n /**\n * Build-time configured file types.\n */\n const TYPES = JSON.parse(PageConfig.getOption('fileTypes') || '{}');\n /**\n * Get a mimetype (or fallback).\n */\n function getType(ext, defaultType = null) {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext && fileType.mimeTypes && fileType.mimeTypes.length) {\n return fileType.mimeTypes[0];\n }\n }\n }\n return mime.getType(ext) || defaultType || MIME.OCTET_STREAM;\n }\n FILE.getType = getType;\n /**\n * Determine whether the given extension matches a given fileFormat.\n */\n function hasFormat(ext, fileFormat) {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n if (fileType.fileFormat !== fileFormat) {\n continue;\n }\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext) {\n return true;\n }\n }\n }\n return false;\n }\n FILE.hasFormat = hasFormat;\n})(FILE || (FILE = {}));\n/**\n * The token for the BroadcastChannel broadcaster.\n */\nexport const IBroadcastChannelWrapper = new Token('@jupyterlite/contents:IBroadcastChannelWrapper');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Token } from '@lumino/coreutils';\n/**\n * The token for the kernels service.\n */\nexport const IKernels = new Token('@jupyterlite/kernel:IKernels');\n/**\n * The kernel name of last resort.\n */\nexport const FALLBACK_KERNEL = 'javascript';\n/**\n * The token for the kernel spec service.\n */\nexport const IKernelSpecs = new Token('@jupyterlite/kernel:IKernelSpecs');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { IServiceWorkerManager, } from '@jupyterlite/server';\nimport { IKernelSpecs } from '@jupyterlite/kernel';\nimport { IBroadcastChannelWrapper } from '@jupyterlite/contents';\nexport * as KERNEL_SETTINGS_SCHEMA from '../schema/kernel.v0.schema.json';\nimport KERNEL_ICON_SVG_STR from '../style/img/pyodide.svg';\nconst KERNEL_ICON_URL = `data:image/svg+xml;base64,${btoa(KERNEL_ICON_SVG_STR)}`;\n/**\n * The default CDN fallback for Pyodide\n */\nconst PYODIDE_CDN_URL = 'https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js';\n/**\n * The id for the extension, and key in the litePlugins.\n */\nconst PLUGIN_ID = '@jupyterlite/pyodide-kernel-extension:kernel';\n/**\n * A plugin to register the Pyodide kernel.\n */\nconst kernel = {\n id: PLUGIN_ID,\n autoStart: true,\n requires: [IKernelSpecs],\n optional: [IServiceWorkerManager, IBroadcastChannelWrapper],\n activate: (app, kernelspecs, serviceWorker, broadcastChannel) => {\n const config = JSON.parse(PageConfig.getOption('litePluginSettings') || '{}')[PLUGIN_ID] || {};\n const url = config.pyodideUrl || PYODIDE_CDN_URL;\n const pyodideUrl = URLExt.parse(url).href;\n const pipliteWheelUrl = config.pipliteWheelUrl\n ? URLExt.parse(config.pipliteWheelUrl).href\n : undefined;\n const rawPipUrls = config.pipliteUrls || [];\n const pipliteUrls = rawPipUrls.map((pipUrl) => URLExt.parse(pipUrl).href);\n const disablePyPIFallback = !!config.disablePyPIFallback;\n kernelspecs.register({\n spec: {\n name: 'python',\n display_name: 'Python (Pyodide)',\n language: 'python',\n argv: [],\n resources: {\n 'logo-32x32': KERNEL_ICON_URL,\n 'logo-64x64': KERNEL_ICON_URL,\n },\n },\n create: async (options) => {\n const { PyodideKernel } = await import('@jupyterlite/pyodide-kernel');\n const mountDrive = !!((serviceWorker === null || serviceWorker === void 0 ? void 0 : serviceWorker.enabled) && (broadcastChannel === null || broadcastChannel === void 0 ? void 0 : broadcastChannel.enabled));\n if (mountDrive) {\n console.info('Pyodide contents will be synced with Jupyter Contents');\n }\n else {\n console.warn('Pyodide contents will NOT be synced with Jupyter Contents');\n }\n return new PyodideKernel({\n ...options,\n pyodideUrl,\n pipliteWheelUrl,\n pipliteUrls,\n disablePyPIFallback,\n mountDrive,\n });\n },\n });\n },\n};\nconst plugins = [kernel];\nexport default plugins;\n","import { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { PathExt } from '@jupyterlab/coreutils';\nimport { MIME, FILE } from './tokens';\nimport { PromiseDelegate } from '@lumino/coreutils';\n/**\n * The name of the local storage.\n */\nconst DEFAULT_STORAGE_NAME = 'JupyterLite Storage';\n/**\n * The number of checkpoints to save.\n */\nconst N_CHECKPOINTS = 5;\n/**\n * A class to handle requests to /api/contents\n */\nexport class Contents {\n /**\n * Construct a new localForage-powered contents provider\n */\n constructor(options) {\n /**\n * A reducer for turning arbitrary binary into a string\n */\n this.reduceBytesToString = (data, byte) => {\n return data + String.fromCharCode(byte);\n };\n this._serverContents = new Map();\n this._storageName = DEFAULT_STORAGE_NAME;\n this._storageDrivers = null;\n this._localforage = options.localforage;\n this._storageName = options.storageName || DEFAULT_STORAGE_NAME;\n this._storageDrivers = options.storageDrivers || null;\n this._ready = new PromiseDelegate();\n }\n /**\n * Finish any initialization after server has started and all extensions are applied.\n */\n async initialize() {\n await this.initStorage();\n this._ready.resolve(void 0);\n }\n /**\n * Initialize all storage instances\n */\n async initStorage() {\n this._storage = this.createDefaultStorage();\n this._counters = this.createDefaultCounters();\n this._checkpoints = this.createDefaultCheckpoints();\n }\n /**\n * A promise that resolves once all storage is fully initialized.\n */\n get ready() {\n return this._ready.promise;\n }\n /**\n * A lazy reference to the underlying storage.\n */\n get storage() {\n return this.ready.then(() => this._storage);\n }\n /**\n * A lazy reference to the underlying counters.\n */\n get counters() {\n return this.ready.then(() => this._counters);\n }\n /**\n * A lazy reference to the underlying checkpoints.\n */\n get checkpoints() {\n return this.ready.then(() => this._checkpoints);\n }\n /**\n * Get default options for localForage instances\n */\n get defaultStorageOptions() {\n const driver = this._storageDrivers && this._storageDrivers.length ? this._storageDrivers : null;\n return {\n version: 1,\n name: this._storageName,\n ...(driver ? { driver } : {}),\n };\n }\n /**\n * Initialize the default storage for contents.\n */\n createDefaultStorage() {\n return this._localforage.createInstance({\n description: 'Offline Storage for Notebooks and Files',\n storeName: 'files',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Initialize the default storage for counting file suffixes.\n */\n createDefaultCounters() {\n return this._localforage.createInstance({\n description: 'Store the current file suffix counters',\n storeName: 'counters',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Create the default checkpoint storage.\n */\n createDefaultCheckpoints() {\n return this._localforage.createInstance({\n description: 'Offline Storage for Checkpoints',\n storeName: 'checkpoints',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the file is created.\n */\n async newUntitled(options) {\n var _a, _b, _c;\n const path = (_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : '';\n const type = (_b = options === null || options === void 0 ? void 0 : options.type) !== null && _b !== void 0 ? _b : 'notebook';\n const created = new Date().toISOString();\n let dirname = PathExt.dirname(path);\n const basename = PathExt.basename(path);\n const extname = PathExt.extname(path);\n const item = await this.get(dirname);\n // handle the case of \"Save As\", where the path points to the new file\n // to create, e.g. subfolder/example-copy.ipynb\n let name = '';\n if (path && !extname && item) {\n // directory\n dirname = `${path}/`;\n name = '';\n }\n else if (dirname && basename) {\n // file in a subfolder\n dirname = `${dirname}/`;\n name = basename;\n }\n else {\n // file at the top level\n dirname = '';\n name = path;\n }\n let file;\n switch (type) {\n case 'directory': {\n const counter = await this._incrementCounter('directory');\n name = `Untitled Folder${counter || ''}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: '',\n content: null,\n size: 0,\n writable: true,\n type: 'directory',\n };\n break;\n }\n case 'notebook': {\n const counter = await this._incrementCounter('notebook');\n name = name || `Untitled${counter || ''}.ipynb`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: MIME.JSON,\n content: Private.EMPTY_NB,\n size: JSON.stringify(Private.EMPTY_NB).length,\n writable: true,\n type: 'notebook',\n };\n break;\n }\n default: {\n const ext = (_c = options === null || options === void 0 ? void 0 : options.ext) !== null && _c !== void 0 ? _c : '.txt';\n const counter = await this._incrementCounter('file');\n const mimetype = FILE.getType(ext) || MIME.OCTET_STREAM;\n let format;\n if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n format = 'text';\n }\n else if (ext.indexOf('json') !== -1 || ext.indexOf('ipynb') !== -1) {\n format = 'json';\n }\n else {\n format = 'base64';\n }\n name = name || `untitled${counter || ''}${ext}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format,\n mimetype,\n content: '',\n size: 0,\n writable: true,\n type: 'file',\n };\n break;\n }\n }\n const key = file.path;\n await (await this.storage).setItem(key, file);\n return file;\n }\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n async copy(path, toDir) {\n let name = PathExt.basename(path);\n toDir = toDir === '' ? '' : `${toDir.slice(1)}/`;\n // TODO: better handle naming collisions with existing files\n while (await this.get(`${toDir}${name}`, { content: true })) {\n const ext = PathExt.extname(name);\n const base = name.replace(ext, '');\n name = `${base} (copy)${ext}`;\n }\n const toPath = `${toDir}${name}`;\n let item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n item = {\n ...item,\n name,\n path: toPath,\n };\n await (await this.storage).setItem(toPath, item);\n return item;\n }\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n async get(path, options) {\n // remove leading slash\n path = decodeURIComponent(path.replace(/^\\//, ''));\n if (path === '') {\n return await this._getFolder(path);\n }\n const storage = await this.storage;\n const item = await storage.getItem(path);\n const serverItem = await this._getServerContents(path, options);\n const model = (item || serverItem);\n if (!model) {\n return null;\n }\n if (!(options === null || options === void 0 ? void 0 : options.content)) {\n return {\n size: 0,\n ...model,\n content: null,\n };\n }\n // for directories, find all files with the path as the prefix\n if (model.type === 'directory') {\n const contentMap = new Map();\n await storage.iterate((file, key) => {\n // use an additional slash to not include the directory itself\n if (key === `${path}/${file.name}`) {\n contentMap.set(file.name, file);\n }\n });\n const serverContents = serverItem\n ? serverItem.content\n : Array.from((await this._getServerDirectory(path)).values());\n for (const file of serverContents) {\n if (!contentMap.has(file.name)) {\n contentMap.set(file.name, file);\n }\n }\n const content = [...contentMap.values()];\n return {\n name: PathExt.basename(path),\n path,\n last_modified: model.last_modified,\n created: model.created,\n format: 'json',\n mimetype: MIME.JSON,\n content,\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n return model;\n }\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the file is renamed.\n */\n async rename(oldLocalPath, newLocalPath) {\n const path = decodeURIComponent(oldLocalPath);\n const file = await this.get(path, { content: true });\n if (!file) {\n throw Error(`Could not find file with path ${path}`);\n }\n const modified = new Date().toISOString();\n const name = PathExt.basename(newLocalPath);\n const newFile = {\n ...file,\n name,\n path: newLocalPath,\n last_modified: modified,\n };\n const storage = await this.storage;\n await storage.setItem(newLocalPath, newFile);\n // remove the old file\n await storage.removeItem(path);\n // remove the corresponding checkpoint\n await (await this.checkpoints).removeItem(path);\n // if a directory, recurse through all children\n if (file.type === 'directory') {\n let child;\n for (child of file.content) {\n await this.rename(URLExt.join(oldLocalPath, child.name), URLExt.join(newLocalPath, child.name));\n }\n }\n return newFile;\n }\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the file is saved.\n */\n async save(path, options = {}) {\n var _a;\n path = decodeURIComponent(path);\n // process the file if coming from an upload\n const ext = PathExt.extname((_a = options.name) !== null && _a !== void 0 ? _a : '');\n const chunk = options.chunk;\n // retrieve the content if it is a later chunk or the last one\n // the new content will then be appended to the existing one\n const chunked = chunk ? chunk > 1 || chunk === -1 : false;\n let item = await this.get(path, { content: chunked });\n if (!item) {\n item = await this.newUntitled({ path, ext, type: 'file' });\n }\n if (!item) {\n return null;\n }\n // keep a reference to the original content\n const originalContent = item.content;\n const modified = new Date().toISOString();\n // override with the new values\n item = {\n ...item,\n ...options,\n last_modified: modified,\n };\n if (options.content && options.format === 'base64') {\n const lastChunk = chunk ? chunk === -1 : true;\n if (ext === '.ipynb') {\n const content = this._handleChunk(options.content, originalContent, chunked);\n item = {\n ...item,\n content: lastChunk ? JSON.parse(content) : content,\n format: 'json',\n type: 'notebook',\n size: content.length,\n };\n }\n else if (FILE.hasFormat(ext, 'json')) {\n const content = this._handleChunk(options.content, originalContent, chunked);\n item = {\n ...item,\n content: lastChunk ? JSON.parse(content) : content,\n format: 'json',\n type: 'file',\n size: content.length,\n };\n }\n else if (FILE.hasFormat(ext, 'text')) {\n const content = this._handleChunk(options.content, originalContent, chunked);\n item = {\n ...item,\n content,\n format: 'text',\n type: 'file',\n size: content.length,\n };\n }\n else {\n const content = options.content;\n item = {\n ...item,\n content,\n size: atob(content).length,\n };\n }\n }\n await (await this.storage).setItem(path, item);\n return item;\n }\n /**\n * Delete a file from browser storage.\n *\n * Has no effect on server-backed files, which will re-appear with their\n * original timestamp.\n *\n * @param path - The path to the file.\n */\n async delete(path) {\n path = decodeURIComponent(path);\n const slashed = `${path}/`;\n const toDelete = (await (await this.storage).keys()).filter((key) => key === path || key.startsWith(slashed));\n await Promise.all(toDelete.map(this.forgetPath, this));\n }\n /**\n * Remove the localForage and checkpoints for a path.\n *\n * @param path - The path to the file\n */\n async forgetPath(path) {\n await Promise.all([\n (await this.storage).removeItem(path),\n (await this.checkpoints).removeItem(path),\n ]);\n }\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n async createCheckpoint(path) {\n var _a;\n const checkpoints = await this.checkpoints;\n path = decodeURIComponent(path);\n const item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n const copies = ((_a = (await checkpoints.getItem(path))) !== null && _a !== void 0 ? _a : []).filter(Boolean);\n copies.push(item);\n // keep only a certain amount of checkpoints per file\n if (copies.length > N_CHECKPOINTS) {\n copies.splice(0, copies.length - N_CHECKPOINTS);\n }\n await checkpoints.setItem(path, copies);\n const id = `${copies.length - 1}`;\n return { id, last_modified: item.last_modified };\n }\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n async listCheckpoints(path) {\n const copies = (await (await this.checkpoints).getItem(path)) || [];\n return copies.filter(Boolean).map(this.normalizeCheckpoint, this);\n }\n normalizeCheckpoint(model, id) {\n return { id: id.toString(), last_modified: model.last_modified };\n }\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n async restoreCheckpoint(path, checkpointID) {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []);\n const id = parseInt(checkpointID);\n const item = copies[id];\n await (await this.storage).setItem(path, item);\n }\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n async deleteCheckpoint(path, checkpointID) {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []);\n const id = parseInt(checkpointID);\n copies.splice(id, 1);\n await (await this.checkpoints).setItem(path, copies);\n }\n /**\n * Handle a chunk of a file.\n * Decode and unescape a base64-encoded string.\n * @param content the content to process\n *\n * @returns the decoded string, appended to the original content if chunked\n * /\n */\n _handleChunk(newContent, originalContent, chunked) {\n const escaped = decodeURIComponent(escape(atob(newContent)));\n const content = chunked ? originalContent + escaped : escaped;\n return content;\n }\n /**\n * retrieve the contents for this path from the union of local storage and\n * `api/contents/{path}/all.json`.\n *\n * @param path - The contents path to retrieve\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n async _getFolder(path) {\n const content = new Map();\n const storage = await this.storage;\n await storage.iterate((file, key) => {\n if (key.includes('/')) {\n return;\n }\n content.set(file.path, file);\n });\n // layer in contents that don't have local overwrites\n for (const file of (await this._getServerDirectory(path)).values()) {\n if (!content.has(file.path)) {\n content.set(file.path, file);\n }\n }\n if (path && content.size === 0) {\n return null;\n }\n return {\n name: '',\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'json',\n mimetype: MIME.JSON,\n content: Array.from(content.values()),\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n /**\n * Attempt to recover the model from `{:path}/__all__.json` file, fall back to\n * deriving the model (including content) off the file in `/files/`. Otherwise\n * return `null`.\n */\n async _getServerContents(path, options) {\n const name = PathExt.basename(path);\n const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));\n let model = parentContents.get(name);\n if (!model) {\n return null;\n }\n model = model || {\n name,\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'text',\n mimetype: MIME.PLAIN_TEXT,\n type: 'file',\n writable: true,\n size: 0,\n content: '',\n };\n if (options === null || options === void 0 ? void 0 : options.content) {\n if (model.type === 'directory') {\n const serverContents = await this._getServerDirectory(path);\n model = { ...model, content: Array.from(serverContents.values()) };\n }\n else {\n const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);\n const response = await fetch(fileUrl);\n if (!response.ok) {\n return null;\n }\n const mimetype = model.mimetype || response.headers.get('Content-Type');\n const ext = PathExt.extname(name);\n if (model.type === 'notebook' ||\n FILE.hasFormat(ext, 'json') ||\n (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||\n path.match(/\\.(ipynb|[^/]*json[^/]*)$/)) {\n const contentText = await response.text();\n model = {\n ...model,\n content: JSON.parse(contentText),\n format: 'json',\n mimetype: model.mimetype || MIME.JSON,\n size: contentText.length,\n };\n }\n else if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n const contentText = await response.text();\n model = {\n ...model,\n content: contentText,\n format: 'text',\n mimetype: mimetype || MIME.PLAIN_TEXT,\n size: contentText.length,\n };\n }\n else {\n const contentBytes = await response.arrayBuffer();\n const contentBuffer = new Uint8Array(contentBytes);\n model = {\n ...model,\n content: btoa(contentBuffer.reduce(this.reduceBytesToString, '')),\n format: 'base64',\n mimetype: mimetype || MIME.OCTET_STREAM,\n size: contentBuffer.length,\n };\n }\n }\n }\n return model;\n }\n /**\n * retrieve the contents for this path from `__index__.json` in the appropriate\n * folder.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n async _getServerDirectory(path) {\n const content = this._serverContents.get(path) || new Map();\n if (!this._serverContents.has(path)) {\n const apiURL = URLExt.join(PageConfig.getBaseUrl(), 'api/contents', path, 'all.json');\n try {\n const response = await fetch(apiURL);\n const json = JSON.parse(await response.text());\n for (const file of json['content']) {\n content.set(file.name, file);\n }\n }\n catch (err) {\n console.warn(`don't worry, about ${err}... nothing's broken. If there had been a\n file at ${apiURL}, you might see some more files.`);\n }\n this._serverContents.set(path, content);\n }\n return content;\n }\n /**\n * Increment the counter for a given file type.\n * Used to avoid collisions when creating new untitled files.\n *\n * @param type The file type to increment the counter for.\n */\n async _incrementCounter(type) {\n var _a;\n const counters = await this.counters;\n const current = (_a = (await counters.getItem(type))) !== null && _a !== void 0 ? _a : -1;\n const counter = current + 1;\n await counters.setItem(type, counter);\n return counter;\n }\n}\n/**\n * A namespace for private data.\n */\nvar Private;\n(function (Private) {\n /**\n * The content for an empty notebook.\n */\n Private.EMPTY_NB = {\n metadata: {\n orig_nbformat: 4,\n },\n nbformat_minor: 4,\n nbformat: 4,\n cells: [],\n };\n})(Private || (Private = {}));\n//# sourceMappingURL=contents.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/// \nexport const DIR_MODE = 16895; // 040777\nexport const FILE_MODE = 33206; // 100666\nexport const SEEK_CUR = 1;\nexport const SEEK_END = 2;\n//# sourceMappingURL=emscripten.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n// Types and implementation inspired from https://github.com/jvilk/BrowserFS\n// LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE\n// And from https://github.com/gzuidhof/starboard-notebook\n// LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE\nimport { DIR_MODE, SEEK_CUR, SEEK_END, } from './emscripten';\nexport const DRIVE_SEPARATOR = ':';\nexport const DRIVE_API_PATH = '/api/drive.v1';\nexport const BLOCK_SIZE = 4096;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n// Mapping flag -> do we need to overwrite the file upon closing it\nconst flagNeedsWrite = {\n 0 /*O_RDONLY*/: false,\n 1 /*O_WRONLY*/: true,\n 2 /*O_RDWR*/: true,\n 64 /*O_CREAT*/: true,\n 65 /*O_WRONLY|O_CREAT*/: true,\n 66 /*O_RDWR|O_CREAT*/: true,\n 129 /*O_WRONLY|O_EXCL*/: true,\n 193 /*O_WRONLY|O_CREAT|O_EXCL*/: true,\n 514 /*O_RDWR|O_TRUNC*/: true,\n 577 /*O_WRONLY|O_CREAT|O_TRUNC*/: true,\n 578 /*O_CREAT|O_RDWR|O_TRUNC*/: true,\n 705 /*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 706 /*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 1024 /*O_APPEND*/: true,\n 1025 /*O_WRONLY|O_APPEND*/: true,\n 1026 /*O_RDWR|O_APPEND*/: true,\n 1089 /*O_WRONLY|O_CREAT|O_APPEND*/: true,\n 1090 /*O_RDWR|O_CREAT|O_APPEND*/: true,\n 1153 /*O_WRONLY|O_EXCL|O_APPEND*/: true,\n 1154 /*O_RDWR|O_EXCL|O_APPEND*/: true,\n 1217 /*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: true,\n 1218 /*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: true,\n 4096 /*O_RDONLY|O_DSYNC*/: true,\n 4098 /*O_RDWR|O_DSYNC*/: true,\n};\nexport class DriveFSEmscriptenStreamOps {\n constructor(fs) {\n this.fs = fs;\n }\n open(stream) {\n const path = this.fs.realPath(stream.node);\n if (this.fs.FS.isFile(stream.node.mode)) {\n stream.file = this.fs.API.get(path);\n }\n }\n close(stream) {\n if (!this.fs.FS.isFile(stream.node.mode) || !stream.file) {\n return;\n }\n const path = this.fs.realPath(stream.node);\n const flags = stream.flags;\n let parsedFlags = typeof flags === 'string' ? parseInt(flags, 10) : flags;\n parsedFlags &= 0x1fff;\n let needsWrite = true;\n if (parsedFlags in flagNeedsWrite) {\n needsWrite = flagNeedsWrite[parsedFlags];\n }\n if (needsWrite) {\n this.fs.API.put(path, stream.file);\n }\n stream.file = undefined;\n }\n read(stream, buffer, offset, length, position) {\n if (length <= 0 ||\n stream.file === undefined ||\n position >= (stream.file.data.length || 0)) {\n return 0;\n }\n const size = Math.min(stream.file.data.length - position, length);\n buffer.set(stream.file.data.subarray(position, position + size), offset);\n return size;\n }\n write(stream, buffer, offset, length, position) {\n var _a;\n if (length <= 0 || stream.file === undefined) {\n return 0;\n }\n stream.node.timestamp = Date.now();\n if (position + length > (((_a = stream.file) === null || _a === void 0 ? void 0 : _a.data.length) || 0)) {\n const oldData = stream.file.data ? stream.file.data : new Uint8Array();\n stream.file.data = new Uint8Array(position + length);\n stream.file.data.set(oldData);\n }\n stream.file.data.set(buffer.subarray(offset, offset + length), position);\n return length;\n }\n llseek(stream, offset, whence) {\n let position = offset;\n if (whence === SEEK_CUR) {\n position += stream.position;\n }\n else if (whence === SEEK_END) {\n if (this.fs.FS.isFile(stream.node.mode)) {\n if (stream.file !== undefined) {\n position += stream.file.data.length;\n }\n else {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM);\n }\n }\n }\n if (position < 0) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EINVAL);\n }\n return position;\n }\n}\nexport class DriveFSEmscriptenNodeOps {\n constructor(fs) {\n this.fs = fs;\n }\n getattr(node) {\n return {\n ...this.fs.API.getattr(this.fs.realPath(node)),\n mode: node.mode,\n ino: node.id,\n };\n }\n setattr(node, attr) {\n for (const [key, value] of Object.entries(attr)) {\n switch (key) {\n case 'mode':\n node.mode = value;\n break;\n case 'timestamp':\n node.timestamp = value;\n break;\n default:\n console.warn('setattr', key, 'of', value, 'on', node, 'not yet implemented');\n break;\n }\n }\n }\n lookup(parent, name) {\n const path = this.fs.PATH.join2(this.fs.realPath(parent), name);\n const result = this.fs.API.lookup(path);\n if (!result.ok) {\n throw this.fs.FS.genericErrors[this.fs.ERRNO_CODES['ENOENT']];\n }\n return this.fs.createNode(parent, name, result.mode, 0);\n }\n mknod(parent, name, mode, dev) {\n const path = this.fs.PATH.join2(this.fs.realPath(parent), name);\n this.fs.API.mknod(path, mode);\n return this.fs.createNode(parent, name, mode, dev);\n }\n rename(oldNode, newDir, newName) {\n this.fs.API.rename(oldNode.parent\n ? this.fs.PATH.join2(this.fs.realPath(oldNode.parent), oldNode.name)\n : oldNode.name, this.fs.PATH.join2(this.fs.realPath(newDir), newName));\n // Updating the in-memory node\n oldNode.name = newName;\n oldNode.parent = newDir;\n }\n unlink(parent, name) {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(parent), name));\n }\n rmdir(parent, name) {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(parent), name));\n }\n readdir(node) {\n return this.fs.API.readdir(this.fs.realPath(node));\n }\n symlink(parent, newName, oldPath) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n readlink(node) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n}\n/**\n * Wrap ServiceWorker requests for an Emscripten-compatible synchronous API.\n */\nexport class ContentsAPI {\n constructor(baseUrl, driveName, mountpoint, FS, ERRNO_CODES) {\n this._baseUrl = baseUrl;\n this._driveName = driveName;\n this._mountpoint = mountpoint;\n this.FS = FS;\n this.ERRNO_CODES = ERRNO_CODES;\n }\n request(data) {\n const xhr = new XMLHttpRequest();\n xhr.open('POST', encodeURI(this.endpoint), false);\n try {\n xhr.send(JSON.stringify(data));\n }\n catch (e) {\n console.error(e);\n }\n if (xhr.status >= 400) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n return JSON.parse(xhr.responseText);\n }\n lookup(path) {\n return this.request({ method: 'lookup', path: this.normalizePath(path) });\n }\n getmode(path) {\n return Number.parseInt(this.request({ method: 'getmode', path: this.normalizePath(path) }));\n }\n mknod(path, mode) {\n return this.request({\n method: 'mknod',\n path: this.normalizePath(path),\n data: { mode },\n });\n }\n rename(oldPath, newPath) {\n return this.request({\n method: 'rename',\n path: this.normalizePath(oldPath),\n data: { newPath: this.normalizePath(newPath) },\n });\n }\n readdir(path) {\n const dirlist = this.request({\n method: 'readdir',\n path: this.normalizePath(path),\n });\n dirlist.push('.');\n dirlist.push('..');\n return dirlist;\n }\n rmdir(path) {\n return this.request({ method: 'rmdir', path: this.normalizePath(path) });\n }\n get(path) {\n const response = this.request({ method: 'get', path: this.normalizePath(path) });\n const serializedContent = response.content;\n const format = response.format;\n switch (format) {\n case 'json':\n case 'text':\n return {\n data: encoder.encode(serializedContent),\n format,\n };\n case 'base64': {\n const binString = atob(serializedContent);\n const len = binString.length;\n const data = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n data[i] = binString.charCodeAt(i);\n }\n return {\n data,\n format,\n };\n }\n default:\n throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);\n }\n }\n put(path, value) {\n switch (value.format) {\n case 'json':\n case 'text':\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: decoder.decode(value.data),\n },\n });\n case 'base64': {\n let binary = '';\n for (let i = 0; i < value.data.byteLength; i++) {\n binary += String.fromCharCode(value.data[i]);\n }\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: btoa(binary),\n },\n });\n }\n }\n }\n getattr(path) {\n const stats = this.request({\n method: 'getattr',\n path: this.normalizePath(path),\n });\n // Turn datetimes into proper objects\n stats.atime = new Date(stats.atime);\n stats.mtime = new Date(stats.mtime);\n stats.ctime = new Date(stats.ctime);\n // ensure a non-undefined size (0 isn't great, though)\n stats.size = stats.size || 0;\n return stats;\n }\n /**\n * Normalize a Path by making it compliant for the content manager\n *\n * @param path: the path relatively to the Emscripten drive\n */\n normalizePath(path) {\n // Remove mountpoint prefix\n if (path.startsWith(this._mountpoint)) {\n path = path.slice(this._mountpoint.length);\n }\n // Add JupyterLab drive name\n if (this._driveName) {\n path = `${this._driveName}${DRIVE_SEPARATOR}${path}`;\n }\n return path;\n }\n /**\n * Get the api/drive endpoint\n */\n get endpoint() {\n return `${this._baseUrl}api/drive`;\n }\n}\nexport class DriveFS {\n constructor(options) {\n this.FS = options.FS;\n this.PATH = options.PATH;\n this.ERRNO_CODES = options.ERRNO_CODES;\n this.API = new ContentsAPI(options.baseUrl, options.driveName, options.mountpoint, this.FS, this.ERRNO_CODES);\n this.driveName = options.driveName;\n this.node_ops = new DriveFSEmscriptenNodeOps(this);\n this.stream_ops = new DriveFSEmscriptenStreamOps(this);\n }\n mount(mount) {\n return this.createNode(null, mount.mountpoint, DIR_MODE | 511, 0);\n }\n createNode(parent, name, mode, dev) {\n const FS = this.FS;\n if (!FS.isDir(mode) && !FS.isFile(mode)) {\n throw new FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n const node = FS.createNode(parent, name, mode, dev);\n node.node_ops = this.node_ops;\n node.stream_ops = this.stream_ops;\n return node;\n }\n getMode(path) {\n return this.API.getmode(path);\n }\n realPath(node) {\n const parts = [];\n let currentNode = node;\n parts.push(currentNode.name);\n while (currentNode.parent !== currentNode) {\n currentNode = currentNode.parent;\n parts.push(currentNode.name);\n }\n parts.reverse();\n return this.PATH.join.apply(null, parts);\n }\n}\n//# sourceMappingURL=drivefs.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { PathExt } from '@jupyterlab/coreutils';\nimport { DIR_MODE, FILE_MODE } from './emscripten';\nimport { BLOCK_SIZE, DRIVE_API_PATH } from './drivefs';\n/** A broadcaster for the ServiceWorker */\nexport class BroadcastChannelWrapper {\n constructor(options) {\n this.isDisposed = false;\n /** Handle a message received on the BroadcastChannel */\n this._onMessage = async (event) => {\n if (!this._channel) {\n return;\n }\n const { _contents } = this;\n const request = event.data;\n const path = request === null || request === void 0 ? void 0 : request.path;\n const receiver = request === null || request === void 0 ? void 0 : request.receiver;\n if (receiver !== 'broadcast.ts') {\n // Message is not meant for us\n return;\n }\n // many successful responses default to null\n let response = null;\n // most requests will use a model\n let model;\n switch (request === null || request === void 0 ? void 0 : request.method) {\n case 'readdir':\n model = await _contents.get(path, { content: true });\n response = [];\n if (model.type === 'directory' && model.content) {\n response = model.content.map((subcontent) => subcontent.name);\n }\n break;\n case 'rmdir':\n await _contents.delete(path);\n break;\n case 'rename':\n await _contents.rename(path, request.data.newPath);\n break;\n case 'getmode':\n model = await _contents.get(path);\n if (model.type === 'directory') {\n response = DIR_MODE;\n }\n else {\n response = FILE_MODE;\n }\n break;\n case 'lookup':\n try {\n model = await _contents.get(path);\n response = {\n ok: true,\n mode: model.type === 'directory' ? DIR_MODE : FILE_MODE,\n };\n }\n catch (e) {\n response = { ok: false };\n }\n break;\n case 'mknod':\n model = await _contents.newUntitled({\n path: PathExt.dirname(path),\n type: Number.parseInt(request.data.mode) === DIR_MODE ? 'directory' : 'file',\n ext: PathExt.extname(path),\n });\n await _contents.rename(model.path, path);\n break;\n case 'getattr': {\n model = await _contents.get(path);\n // create a default date for drives that send incomplete information\n // for nested foldes and files\n const defaultDate = new Date(0).toISOString();\n response = {\n dev: 1,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n size: model.size || 0,\n blksize: BLOCK_SIZE,\n blocks: Math.ceil(model.size || 0 / BLOCK_SIZE),\n atime: model.last_modified || defaultDate,\n mtime: model.last_modified || defaultDate,\n ctime: model.created || defaultDate,\n timestamp: 0,\n };\n break;\n }\n case 'get':\n model = await _contents.get(path, { content: true });\n if (model.type === 'directory') {\n break;\n }\n response = {\n content: model.format === 'json' ? JSON.stringify(model.content) : model.content,\n format: model.format,\n };\n break;\n case 'put':\n await _contents.save(path, {\n content: request.data.format === 'json'\n ? JSON.parse(request.data.data)\n : request.data.data,\n type: 'file',\n format: request.data.format,\n });\n break;\n default:\n response = null;\n break;\n }\n this._channel.postMessage(response);\n };\n this._channel = null;\n this._enabled = false;\n this._contents = options.contents;\n }\n get enabled() {\n return this._enabled;\n }\n enable() {\n if (this._channel) {\n console.warn('BroadcastChannel already created and enabled');\n return;\n }\n this._channel = new BroadcastChannel(DRIVE_API_PATH);\n this._channel.addEventListener('message', this._onMessage);\n this._enabled = true;\n }\n disable() {\n if (this._channel) {\n this._channel.removeEventListener('message', this._onMessage);\n this._channel = null;\n }\n this._enabled = false;\n }\n /** Clean up the broadcaster. */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this.disable();\n this.isDisposed = true;\n }\n}\n//# sourceMappingURL=broadcast.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Signal } from '@lumino/signaling';\n/**\n * A concrete implementation of IObservableMap.\n */\nexport class ObservableMap {\n /**\n * Construct a new observable map.\n */\n constructor(options = {}) {\n this._map = new Map();\n this._changed = new Signal(this);\n this._isDisposed = false;\n this._itemCmp = options.itemCmp || Private.itemCmp;\n if (options.values) {\n for (const key in options.values) {\n this._map.set(key, options.values[key]);\n }\n }\n }\n /**\n * The type of the Observable.\n */\n get type() {\n return 'Map';\n }\n /**\n * A signal emitted when the map has changed.\n */\n get changed() {\n return this._changed;\n }\n /**\n * Whether this map has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * The number of key-value pairs in the map.\n */\n get size() {\n return this._map.size;\n }\n /**\n * Set a key-value pair in the map\n *\n * @param key - The key to set.\n *\n * @param value - The value for the key.\n *\n * @returns the old value for the key, or undefined\n * if that did not exist.\n *\n * @throws if the new value is undefined.\n *\n * #### Notes\n * This is a no-op if the value does not change.\n */\n set(key, value) {\n const oldVal = this._map.get(key);\n if (value === undefined) {\n throw Error('Cannot set an undefined value, use remove');\n }\n // Bail if the value does not change.\n const itemCmp = this._itemCmp;\n if (oldVal !== undefined && itemCmp(oldVal, value)) {\n return oldVal;\n }\n this._map.set(key, value);\n this._changed.emit({\n type: oldVal ? 'change' : 'add',\n key: key,\n oldValue: oldVal,\n newValue: value\n });\n return oldVal;\n }\n /**\n * Get a value for a given key.\n *\n * @param key - the key.\n *\n * @returns the value for that key.\n */\n get(key) {\n return this._map.get(key);\n }\n /**\n * Check whether the map has a key.\n *\n * @param key - the key to check.\n *\n * @returns `true` if the map has the key, `false` otherwise.\n */\n has(key) {\n return this._map.has(key);\n }\n /**\n * Get a list of the keys in the map.\n *\n * @returns - a list of keys.\n */\n keys() {\n const keyList = [];\n this._map.forEach((v, k) => {\n keyList.push(k);\n });\n return keyList;\n }\n /**\n * Get a list of the values in the map.\n *\n * @returns - a list of values.\n */\n values() {\n const valList = [];\n this._map.forEach((v, k) => {\n valList.push(v);\n });\n return valList;\n }\n /**\n * Remove a key from the map\n *\n * @param key - the key to remove.\n *\n * @returns the value of the given key,\n * or undefined if that does not exist.\n *\n * #### Notes\n * This is a no-op if the value does not change.\n */\n delete(key) {\n const oldVal = this._map.get(key);\n const removed = this._map.delete(key);\n if (removed) {\n this._changed.emit({\n type: 'remove',\n key: key,\n oldValue: oldVal,\n newValue: undefined\n });\n }\n return oldVal;\n }\n /**\n * Set the ObservableMap to an empty map.\n */\n clear() {\n // Delete one by one to emit the correct signals.\n const keyList = this.keys();\n for (let i = 0; i < keyList.length; i++) {\n this.delete(keyList[i]);\n }\n }\n /**\n * Dispose of the resources held by the map.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n this._map.clear();\n }\n}\n/**\n * The namespace for module private data.\n */\nvar Private;\n(function (Private) {\n /**\n * The default strict equality item comparator.\n */\n function itemCmp(first, second) {\n return first === second;\n }\n Private.itemCmp = itemCmp;\n})(Private || (Private = {}));\n//# sourceMappingURL=observablemap.js.map","const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_maxConcurrency, _cancelError = E_CANCELED) {\n this._maxConcurrency = _maxConcurrency;\n this._cancelError = _cancelError;\n this._queue = [];\n this._waiters = [];\n if (_maxConcurrency <= 0) {\n throw new Error('semaphore must be initialized to a positive value');\n }\n this._value = _maxConcurrency;\n }\n acquire() {\n const locked = this.isLocked();\n const ticketPromise = new Promise((resolve, reject) => this._queue.push({ resolve, reject }));\n if (!locked)\n this._dispatch();\n return ticketPromise;\n }\n runExclusive(callback) {\n return __awaiter$2(this, void 0, void 0, function* () {\n const [value, release] = yield this.acquire();\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock() {\n return __awaiter$2(this, void 0, void 0, function* () {\n if (!this.isLocked()) {\n return Promise.resolve();\n }\n const waitPromise = new Promise((resolve) => this._waiters.push({ resolve }));\n return waitPromise;\n });\n }\n isLocked() {\n return this._value <= 0;\n }\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release() {\n if (this._maxConcurrency > 1) {\n throw new Error('this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead');\n }\n if (this._currentReleaser) {\n const releaser = this._currentReleaser;\n this._currentReleaser = undefined;\n releaser();\n }\n }\n cancel() {\n this._queue.forEach((ticket) => ticket.reject(this._cancelError));\n this._queue = [];\n }\n _dispatch() {\n const nextTicket = this._queue.shift();\n if (!nextTicket)\n return;\n let released = false;\n this._currentReleaser = () => {\n if (released)\n return;\n released = true;\n this._value++;\n this._resolveWaiters();\n this._dispatch();\n };\n nextTicket.resolve([this._value--, this._currentReleaser]);\n }\n _resolveWaiters() {\n this._waiters.forEach((waiter) => waiter.resolve());\n this._waiters = [];\n }\n}\n\nvar __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, void 0, void 0, function* () {\n const [, releaser] = yield this._semaphore.acquire();\n return releaser;\n });\n }\n runExclusive(callback) {\n return this._semaphore.runExclusive(() => callback());\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock() {\n return this._semaphore.waitForUnlock();\n }\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release() {\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: () => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield sync.acquire();\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n })),\n runExclusive(callback) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire();\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release() {\n sync.release();\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: () => sync.waitForUnlock(),\n isLocked: () => sync.isLocked(),\n };\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\nexport { E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Mutex, Semaphore, tryAcquire, withTimeout };\n","import { ObservableMap } from '@jupyterlab/observables';\nimport { deserialize, serialize } from '@jupyterlab/services/lib/kernel/serialize';\nimport { supportedKernelWebSocketProtocols } from '@jupyterlab/services/lib/kernel/messages';\nimport { UUID } from '@lumino/coreutils';\nimport { Server as WebSocketServer } from 'mock-socket';\nimport { Mutex } from 'async-mutex';\nimport { PageConfig } from '@jupyterlab/coreutils';\n/**\n * Use the default kernel wire protocol.\n */\nconst KERNEL_WEBSOCKET_PROTOCOL = supportedKernelWebSocketProtocols.v1KernelWebsocketJupyterOrg;\n/**\n * A class to handle requests to /api/kernels\n */\nexport class Kernels {\n /**\n * Construct a new Kernels\n *\n * @param options The instantiation options\n */\n constructor(options) {\n this._kernels = new ObservableMap();\n this._clients = new ObservableMap();\n this._kernelClients = new ObservableMap();\n const { kernelspecs } = options;\n this._kernelspecs = kernelspecs;\n }\n /**\n * Start a new kernel.\n *\n * @param options The kernel start options.\n */\n async startNew(options) {\n const { id, name, location } = options;\n const factory = this._kernelspecs.factories.get(name);\n // bail if there is no factory associated with the requested kernel\n if (!factory) {\n return { id, name };\n }\n // create a synchronization mechanism to allow only one message\n // to be processed at a time\n const mutex = new Mutex();\n // hook a new client to a kernel\n const hook = (kernelId, clientId, socket) => {\n var _a;\n const kernel = this._kernels.get(kernelId);\n if (!kernel) {\n throw Error(`No kernel ${kernelId}`);\n }\n this._clients.set(clientId, socket);\n (_a = this._kernelClients.get(kernelId)) === null || _a === void 0 ? void 0 : _a.add(clientId);\n const processMsg = async (msg) => {\n await mutex.runExclusive(async () => {\n await kernel.ready;\n await kernel.handleMessage(msg);\n });\n };\n socket.on('message', async (message) => {\n let msg;\n if (message instanceof ArrayBuffer) {\n message = new Uint8Array(message).buffer;\n msg = deserialize(message, KERNEL_WEBSOCKET_PROTOCOL);\n }\n else if (typeof message === 'string') {\n const encoder = new TextEncoder();\n const encodedData = encoder.encode(message);\n msg = deserialize(encodedData.buffer, KERNEL_WEBSOCKET_PROTOCOL);\n }\n else {\n return;\n }\n // TODO Find a better solution for this?\n // input-reply is asynchronous, must not be processed like other messages\n if (msg.header.msg_type === 'input_reply') {\n kernel.handleMessage(msg);\n }\n else {\n void processMsg(msg);\n }\n });\n const removeClient = () => {\n var _a;\n this._clients.delete(clientId);\n (_a = this._kernelClients.get(kernelId)) === null || _a === void 0 ? void 0 : _a.delete(clientId);\n };\n kernel.disposed.connect(removeClient);\n // TODO: check whether this is called\n // https://github.com/thoov/mock-socket/issues/298\n // https://github.com/jupyterlab/jupyterlab/blob/6bc884a7a8ed73c615ce72ba097bdb790482b5bf/packages/services/src/kernel/default.ts#L1245\n socket.onclose = removeClient;\n };\n // ensure kernel id\n const kernelId = id !== null && id !== void 0 ? id : UUID.uuid4();\n // There is one server per kernel which handles multiple clients\n const kernelUrl = `${Kernels.WS_BASE_URL}api/kernels/${kernelId}/channels`;\n const runningKernel = this._kernels.get(kernelId);\n if (runningKernel) {\n return {\n id: runningKernel.id,\n name: runningKernel.name,\n };\n }\n // start the kernel\n const sendMessage = (msg) => {\n const clientId = msg.header.session;\n const socket = this._clients.get(clientId);\n if (!socket) {\n console.warn(`Trying to send message on removed socket for kernel ${kernelId}`);\n return;\n }\n const message = serialize(msg, KERNEL_WEBSOCKET_PROTOCOL);\n // process iopub messages\n if (msg.channel === 'iopub') {\n const clients = this._kernelClients.get(kernelId);\n clients === null || clients === void 0 ? void 0 : clients.forEach((id) => {\n var _a;\n (_a = this._clients.get(id)) === null || _a === void 0 ? void 0 : _a.send(message);\n });\n return;\n }\n socket.send(message);\n };\n const kernel = await factory({\n id: kernelId,\n sendMessage,\n name,\n location,\n });\n this._kernels.set(kernelId, kernel);\n this._kernelClients.set(kernelId, new Set());\n // create the websocket server for the kernel\n const wsServer = new WebSocketServer(kernelUrl, {\n mock: false,\n selectProtocol: () => KERNEL_WEBSOCKET_PROTOCOL,\n });\n wsServer.on('connection', (socket) => {\n var _a;\n const url = new URL(socket.url);\n const clientId = (_a = url.searchParams.get('session_id')) !== null && _a !== void 0 ? _a : '';\n hook(kernelId, clientId, socket);\n });\n // clean up closed connection\n wsServer.on('close', () => {\n this._clients.keys().forEach((clientId) => {\n var _a;\n const socket = this._clients.get(clientId);\n if ((socket === null || socket === void 0 ? void 0 : socket.readyState) === WebSocket.CLOSED) {\n this._clients.delete(clientId);\n (_a = this._kernelClients.get(kernelId)) === null || _a === void 0 ? void 0 : _a.delete(clientId);\n }\n });\n });\n // cleanup on kernel shutdown\n kernel.disposed.connect(() => {\n wsServer.close();\n this._kernels.delete(kernelId);\n this._kernelClients.delete(kernelId);\n });\n return {\n id: kernel.id,\n name: kernel.name,\n };\n }\n /**\n * Restart a kernel.\n *\n * @param kernelId The kernel id.\n */\n async restart(kernelId) {\n const kernel = this._kernels.get(kernelId);\n if (!kernel) {\n throw Error(`Kernel ${kernelId} does not exist`);\n }\n const { id, name, location } = kernel;\n kernel.dispose();\n return this.startNew({ id, name, location });\n }\n /**\n * List the running kernels.\n */\n async list() {\n return [...this._kernels.values()].map((kernel) => ({\n id: kernel.id,\n name: kernel.name,\n }));\n }\n /**\n * Shut down a kernel.\n *\n * @param id The kernel id.\n */\n async shutdown(id) {\n var _a;\n (_a = this._kernels.delete(id)) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n /**\n * Get a kernel by id\n */\n async get(id) {\n return this._kernels.get(id);\n }\n}\n/**\n * A namespace for Kernels statics.\n */\n(function (Kernels) {\n /**\n * The base url for the Kernels manager\n */\n Kernels.WS_BASE_URL = PageConfig.getBaseUrl().replace(/^http/, 'ws');\n})(Kernels || (Kernels = {}));\n//# sourceMappingURL=kernels.js.map","import { PageConfig } from '@jupyterlab/coreutils';\nimport { FALLBACK_KERNEL } from './tokens';\n/**\n * A class to handle requests to /api/kernelspecs\n */\nexport class KernelSpecs {\n constructor() {\n this._specs = new Map();\n this._factories = new Map();\n }\n /**\n * Get the kernel specs.\n */\n get specs() {\n if (this._specs.size === 0) {\n return null;\n }\n return {\n default: this.defaultKernelName,\n kernelspecs: Object.fromEntries(this._specs),\n };\n }\n /**\n * Get the default kernel name.\n */\n get defaultKernelName() {\n let defaultKernelName = PageConfig.getOption('defaultKernelName');\n if (!defaultKernelName && this._specs.size) {\n const keys = Array.from(this._specs.keys());\n keys.sort();\n defaultKernelName = keys[0];\n }\n return defaultKernelName || FALLBACK_KERNEL;\n }\n /**\n * Get the kernel factories for the current kernels.\n */\n get factories() {\n return this._factories;\n }\n /**\n * Register a new kernel.\n *\n * @param options The options to register a new kernel.\n */\n register(options) {\n const { spec, create } = options;\n this._specs.set(spec.name, spec);\n this._factories.set(spec.name, create);\n }\n}\n//# sourceMappingURL=kernelspecs.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Token } from '@lumino/coreutils';\n/**\n * The well-known name of the file. Can actually be configured by alternate\n * implementations, but the default is probably good enough for \"best-effort.\"\n */\nexport const THIRD_PARTY_LICENSES = 'third-party-licenses.json';\n/**\n * The token for the licenses service.\n */\nexport const ILicenses = new Token('@jupyterlite/licenses:ILicenses');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { URLExt, PageConfig } from '@jupyterlab/coreutils';\nimport { THIRD_PARTY_LICENSES, } from './tokens';\n/**\n * An empty bundle.\n */\nconst EMPTY_BUNDLE = Object.freeze({ packages: [] });\n/**\n * A JupyterLite implementation of the jupyterlab_server licenses route\n */\nexport class Licenses {\n /**\n * A GET handler for the licenses\n */\n async get() {\n return {\n bundles: {\n ...(await this._getFederated()),\n [this.appName]: await this._getAppLicenses(),\n },\n };\n }\n /**\n * Get the app name (or default).\n */\n get appName() {\n return PageConfig.getOption('appName') || 'JupyterLite';\n }\n /**\n * Get the well-known URL of the app licenses.\n */\n get appLicensesUrl() {\n return URLExt.join(PageConfig.getBaseUrl(), 'build', THIRD_PARTY_LICENSES);\n }\n /**\n * Get the lab extension base url.\n */\n get labExtensionsUrl() {\n return PageConfig.getOption('fullLabextensionsUrl');\n }\n /**\n * Resolve the licenses for the app distribution itself, or the empty bundle.\n */\n async _getAppLicenses() {\n let bundle = EMPTY_BUNDLE;\n try {\n const response = await fetch(this.appLicensesUrl);\n bundle = response.json();\n }\n catch (err) {\n console.warn('Could not resolve licenses for', this.appName);\n }\n return bundle;\n }\n /**\n * Resolve the licenses for all federated extensions.\n */\n async _getFederated() {\n const bundles = {};\n let federated;\n try {\n federated = JSON.parse(PageConfig.getOption('federated_extensions'));\n }\n catch {\n return bundles;\n }\n const promises = [];\n for (const ext of federated) {\n promises.push(this._getOneFederated(ext, bundles));\n }\n try {\n await Promise.all(promises);\n }\n catch (err) {\n console.warn('Error resolving licenses', err);\n }\n return bundles;\n }\n /**\n * Update the bundles with the extension's licenses, or the empty bundle.\n */\n async _getOneFederated(ext, bundles) {\n try {\n const url = URLExt.join(this.labExtensionsUrl, ext.name, 'static', THIRD_PARTY_LICENSES);\n const response = await fetch(url);\n bundles[ext.name] = await response.json();\n }\n catch {\n console.warn('Could not resolve licenses for', ext);\n bundles[ext.name] = EMPTY_BUNDLE;\n }\n }\n}\n//# sourceMappingURL=licenses.js.map","import { Token } from '@lumino/coreutils';\n/**\n * The token for the sessions service.\n */\nexport const ISessions = new Token('@jupyterlite/session:ISessions');\n//# sourceMappingURL=tokens.js.map","import { PathExt } from '@jupyterlab/coreutils';\nimport { ArrayExt } from '@lumino/algorithm';\nimport { UUID } from '@lumino/coreutils';\n/**\n * A class to handle requests to /api/sessions\n */\nexport class Sessions {\n /**\n * Construct a new Sessions.\n *\n * @param options The instantiation options for a Sessions.\n */\n constructor(options) {\n // TODO: offload to a database\n this._sessions = [];\n this._kernels = options.kernels;\n }\n /**\n * Get a session by id.\n *\n * @param id The id of the session.\n */\n async get(id) {\n const session = this._sessions.find((s) => s.id === id);\n if (!session) {\n throw Error(`Session ${id} not found`);\n }\n return session;\n }\n /**\n * List the running sessions\n */\n async list() {\n return this._sessions;\n }\n /**\n * Path an existing session.\n * This can be used to rename a session.\n *\n * - path updates session to track renamed paths\n * - kernel.name starts a new kernel with a given kernelspec\n *\n * @param options The options to patch the session.\n */\n async patch(options) {\n const { id, path, name, kernel } = options;\n const index = this._sessions.findIndex((s) => s.id === id);\n const session = this._sessions[index];\n if (!session) {\n throw Error(`Session ${id} not found`);\n }\n const patched = {\n ...session,\n path: path !== null && path !== void 0 ? path : session.path,\n name: name !== null && name !== void 0 ? name : session.name,\n };\n if (kernel) {\n // Kernel id takes precedence over name.\n if (kernel.id) {\n const session = this._sessions.find((session) => { var _a; return ((_a = session.kernel) === null || _a === void 0 ? void 0 : _a.id) === (kernel === null || kernel === void 0 ? void 0 : kernel.id); });\n if (session) {\n patched.kernel = session.kernel;\n }\n }\n else if (kernel.name) {\n const newKernel = await this._kernels.startNew({\n id: UUID.uuid4(),\n name: kernel.name,\n location: PathExt.dirname(patched.path),\n });\n if (newKernel) {\n patched.kernel = newKernel;\n }\n // clean up the session on kernel shutdown\n void this._handleKernelShutdown({\n kernelId: newKernel.id,\n sessionId: session.id,\n });\n }\n }\n this._sessions[index] = patched;\n return patched;\n }\n /**\n * Start a new session\n * TODO: read path and name\n *\n * @param options The options to start a new session.\n */\n async startNew(options) {\n var _a, _b, _c, _d;\n const { path, name } = options;\n const running = this._sessions.find((s) => s.name === name);\n if (running) {\n return running;\n }\n const kernelName = (_b = (_a = options.kernel) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : '';\n const id = (_c = options.id) !== null && _c !== void 0 ? _c : UUID.uuid4();\n const nameOrPath = (_d = options.name) !== null && _d !== void 0 ? _d : options.path;\n const dirname = PathExt.dirname(options.name) || PathExt.dirname(options.path);\n const hasDrive = nameOrPath.includes(':');\n const driveName = hasDrive ? nameOrPath.split(':')[0] : '';\n // add drive name if missing (top level directory)\n const location = dirname.includes(driveName) ? dirname : `${driveName}:${dirname}`;\n const kernel = await this._kernels.startNew({\n id,\n name: kernelName,\n location,\n });\n const session = {\n id,\n path,\n name: name !== null && name !== void 0 ? name : path,\n type: 'notebook',\n kernel: {\n id: kernel.id,\n name: kernel.name,\n },\n };\n this._sessions.push(session);\n // clean up the session on kernel shutdown\n void this._handleKernelShutdown({ kernelId: id, sessionId: session.id });\n return session;\n }\n /**\n * Shut down a session.\n *\n * @param id The id of the session to shut down.\n */\n async shutdown(id) {\n var _a;\n const session = this._sessions.find((s) => s.id === id);\n if (!session) {\n throw Error(`Session ${id} not found`);\n }\n const kernelId = (_a = session.kernel) === null || _a === void 0 ? void 0 : _a.id;\n if (kernelId) {\n await this._kernels.shutdown(kernelId);\n }\n ArrayExt.removeFirstOf(this._sessions, session);\n }\n /**\n * Handle kernel shutdown\n */\n async _handleKernelShutdown({ kernelId, sessionId, }) {\n const runningKernel = await this._kernels.get(kernelId);\n if (runningKernel) {\n runningKernel.disposed.connect(() => {\n this.shutdown(sessionId);\n });\n }\n }\n}\n//# sourceMappingURL=sessions.js.map","import { Token } from '@lumino/coreutils';\n/**\n * The token for the settings service.\n */\nexport const ISettings = new Token('@jupyterlite/settings:ISettings');\n//# sourceMappingURL=tokens.js.map","import { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport * as json5 from 'json5';\n/**\n * The name of the local storage.\n */\nconst DEFAULT_STORAGE_NAME = 'JupyterLite Storage';\n/**\n * A class to handle requests to /api/settings\n */\nexport class Settings {\n constructor(options) {\n this._storageName = DEFAULT_STORAGE_NAME;\n this._storageDrivers = null;\n this._localforage = options.localforage;\n this._storageName = options.storageName || DEFAULT_STORAGE_NAME;\n this._storageDrivers = options.storageDrivers || null;\n this._ready = new PromiseDelegate();\n }\n /**\n * A promise that resolves when the settings storage is fully initialized\n */\n get ready() {\n return this._ready.promise;\n }\n /**\n * A lazy reference to initialized storage\n */\n get storage() {\n return this.ready.then(() => this._storage);\n }\n /**\n * Finish any initialization after server has started and all extensions are applied.\n */\n async initialize() {\n await this.initStorage();\n this._ready.resolve(void 0);\n }\n /**\n * Prepare the storage\n */\n async initStorage() {\n this._storage = this.defaultSettingsStorage();\n }\n /**\n * Get default options for localForage instances\n */\n get defaultStorageOptions() {\n var _a;\n const driver = ((_a = this._storageDrivers) === null || _a === void 0 ? void 0 : _a.length) ? this._storageDrivers : null;\n return {\n version: 1,\n name: this._storageName,\n ...(driver ? { driver } : {}),\n };\n }\n /**\n * Create a settings store.\n */\n defaultSettingsStorage() {\n return this._localforage.createInstance({\n description: 'Offline Storage for Settings',\n storeName: 'settings',\n ...this.defaultStorageOptions,\n });\n }\n /**\n * Get settings by plugin id\n *\n * @param pluginId the id of the plugin\n *\n */\n async get(pluginId) {\n const all = await this.getAll();\n const settings = all.settings;\n const setting = settings.find((setting) => {\n return setting.id === pluginId;\n });\n return setting;\n }\n /**\n * Get all the settings\n */\n async getAll() {\n const [allCore, allFederated] = await Promise.all([\n this._getAll('all.json'),\n this._getAll('all_federated.json'),\n ]);\n // JupyterLab 4 expects all settings to be returned in one go\n // so append the settings from federated plugins to the core ones\n const all = allCore.concat(allFederated);\n // return existing user settings if they exist\n const storage = await this.storage;\n const settings = await Promise.all(all.map(async (plugin) => {\n var _a;\n const { id } = plugin;\n const raw = (_a = (await storage.getItem(id))) !== null && _a !== void 0 ? _a : plugin.raw;\n return {\n ...Private.override(plugin),\n raw,\n settings: json5.parse(raw),\n };\n }));\n return { settings };\n }\n /**\n * Save settings for a given plugin id\n *\n * @param pluginId The id of the plugin\n * @param raw The raw settings\n *\n */\n async save(pluginId, raw) {\n await (await this.storage).setItem(pluginId, raw);\n }\n /**\n * Get all the settings for core or federated plugins\n */\n async _getAll(file) {\n var _a;\n const settingsUrl = (_a = PageConfig.getOption('settingsUrl')) !== null && _a !== void 0 ? _a : '/';\n const all = (await (await fetch(URLExt.join(settingsUrl, file))).json());\n return all;\n }\n}\n/**\n * A namespace for private data\n */\nvar Private;\n(function (Private) {\n const _overrides = JSON.parse(PageConfig.getOption('settingsOverrides') || '{}');\n /**\n * Override the defaults of the schema with ones from PageConfig\n *\n * @see https://github.com/jupyterlab/jupyterlab_server/blob/v2.5.2/jupyterlab_server/settings_handler.py#L216-L227\n */\n function override(plugin) {\n if (_overrides[plugin.id]) {\n if (!plugin.schema.properties) {\n // probably malformed, or only provides keyboard shortcuts, etc.\n plugin.schema.properties = {};\n }\n for (const [prop, propDefault] of Object.entries(_overrides[plugin.id] || {})) {\n plugin.schema.properties[prop].default = propDefault;\n }\n }\n return plugin;\n }\n Private.override = override;\n})(Private || (Private = {}));\n//# sourceMappingURL=settings.js.map","import { Token } from '@lumino/coreutils';\n/**\n * The token for the settings service.\n */\nexport const ITranslation = new Token('@jupyterlite/translation:ITranslation');\n//# sourceMappingURL=tokens.js.map","import { PageConfig, URLExt } from '@jupyterlab/coreutils';\n/**\n * A fake locale to retrieve all the language packs.\n */\nconst ALL = 'all';\n/**\n * A class to handle requests to /api/translations\n */\nexport class Translation {\n constructor() {\n this._prevLocale = '';\n }\n /**\n * Get the translation data for the given locale\n * @param locale The locale\n * @returns\n */\n async get(locale) {\n const apiURL = URLExt.join(PageConfig.getBaseUrl(), `api/translations/${locale}.json`);\n try {\n const response = await fetch(apiURL);\n const json = JSON.parse(await response.text());\n if (this._prevLocale !== ALL && locale === ALL) {\n // TODO: fix this logic upstream?\n // the upstream translation plugin relies on the comparison between\n // the display name and the native name to enable or disable the commands:\n // https://github.com/jupyterlab/jupyterlab/blob/befa831ffef36321b87f352a48fbe2439df6c872/packages/translation-extension/src/index.ts#L117\n const prev = this._prevLocale;\n json.data[prev].displayName = json.data[prev].nativeName;\n if (prev !== 'en') {\n json.data['en'].displayName = `${json.data['en'].nativeName} (default)`;\n }\n }\n this._prevLocale = locale;\n return json;\n }\n catch (e) {\n if (locale) {\n return {\n data: {},\n message: `Language pack '${locale}' not installed!`,\n };\n }\n return {\n data: {\n en: { displayName: 'English', nativeName: 'English' },\n },\n message: '',\n };\n }\n }\n}\n//# sourceMappingURL=translation.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { Token } from '@lumino/coreutils';\n/**\n * The token for the localforage singleton.\n */\nexport const ILocalForage = new Token('@jupyterlite/localforge:ILocalForage');\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport { BroadcastChannelWrapper, Contents, IContents, IBroadcastChannelWrapper, } from '@jupyterlite/contents';\nimport { IKernels, Kernels, IKernelSpecs, KernelSpecs } from '@jupyterlite/kernel';\nimport { ILicenses, Licenses } from '@jupyterlite/licenses';\nimport { IServiceWorkerManager, ServiceWorkerManager, } from '@jupyterlite/server';\nimport { ISessions, Sessions } from '@jupyterlite/session';\nimport { ISettings, Settings } from '@jupyterlite/settings';\nimport { ITranslation, Translation } from '@jupyterlite/translation';\nimport { ILocalForage, ensureMemoryStorage } from '@jupyterlite/localforage';\nimport localforage from 'localforage';\n/**\n * The localforage plugin\n */\nconst localforagePlugin = {\n id: '@jupyterlite/server-extension:localforage',\n autoStart: true,\n provides: ILocalForage,\n activate: (app) => {\n return { localforage };\n },\n};\n/**\n * The volatile localforage memory plugin\n */\nconst localforageMemoryPlugin = {\n id: '@jupyterlite/server-extension:localforage-memory-storage',\n autoStart: true,\n requires: [ILocalForage],\n activate: async (app, forage) => {\n if (JSON.parse(PageConfig.getOption('enableMemoryStorage') || 'false')) {\n console.warn('Memory storage fallback enabled: contents and settings may not be saved');\n await ensureMemoryStorage(forage.localforage);\n }\n },\n};\n/**\n * The contents service plugin.\n */\nconst contentsPlugin = {\n id: '@jupyterlite/server-extension:contents',\n requires: [ILocalForage],\n autoStart: true,\n provides: IContents,\n activate: (app, forage) => {\n const storageName = PageConfig.getOption('contentsStorageName');\n const storageDrivers = JSON.parse(PageConfig.getOption('contentsStorageDrivers') || 'null');\n const { localforage } = forage;\n const contents = new Contents({\n storageName,\n storageDrivers,\n localforage,\n });\n app.started.then(() => contents.initialize().catch(console.warn));\n return contents;\n },\n};\n/**\n * A plugin providing the routes for the contents service.\n */\nconst contentsRoutesPlugin = {\n id: '@jupyterlite/server-extension:contents-routes',\n autoStart: true,\n requires: [IContents],\n activate: (app, contents) => {\n // GET /api/contents/{path}/checkpoints - Get a list of checkpoints for a file\n app.router.get('/api/contents/(.+)/checkpoints', async (req, filename) => {\n const res = await contents.listCheckpoints(filename);\n return new Response(JSON.stringify(res));\n });\n // POST /api/contents/{path}/checkpoints/{checkpoint_id} - Restore a file to a particular checkpointed state\n app.router.post('/api/contents/(.+)/checkpoints/(.*)', async (req, filename, checkpoint) => {\n const res = await contents.restoreCheckpoint(filename, checkpoint);\n return new Response(JSON.stringify(res), { status: 204 });\n });\n // POST /api/contents/{path}/checkpoints - Create a new checkpoint for a file\n app.router.post('/api/contents/(.+)/checkpoints', async (req, filename) => {\n const res = await contents.createCheckpoint(filename);\n return new Response(JSON.stringify(res), { status: 201 });\n });\n // DELETE /api/contents/{path}/checkpoints/{checkpoint_id} - Delete a checkpoint\n app.router.delete('/api/contents/(.+)/checkpoints/(.*)', async (req, filename, checkpoint) => {\n const res = await contents.deleteCheckpoint(filename, checkpoint);\n return new Response(JSON.stringify(res), { status: 204 });\n });\n // GET /api/contents/{path} - Get contents of file or directory\n app.router.get('/api/contents(.*)', async (req, filename) => {\n var _a;\n const options = {\n content: ((_a = req.query) === null || _a === void 0 ? void 0 : _a.content) === '1',\n };\n const nb = await contents.get(filename, options);\n if (!nb) {\n return new Response(null, { status: 404 });\n }\n return new Response(JSON.stringify(nb));\n });\n // POST /api/contents/{path} - Create a new file in the specified path\n app.router.post('/api/contents(.*)', async (req, path) => {\n const options = req.body;\n const copyFrom = options === null || options === void 0 ? void 0 : options.copy_from;\n let file;\n if (copyFrom) {\n file = await contents.copy(copyFrom, path);\n }\n else {\n file = await contents.newUntitled(options);\n }\n if (!file) {\n return new Response(null, { status: 400 });\n }\n return new Response(JSON.stringify(file), { status: 201 });\n });\n // PATCH /api/contents/{path} - Rename a file or directory without re-uploading content\n app.router.patch('/api/contents(.*)', async (req, filename) => {\n var _a, _b;\n const newPath = (_b = (_a = req.body) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : '';\n filename = filename[0] === '/' ? filename.slice(1) : filename;\n const nb = await contents.rename(filename, newPath);\n return new Response(JSON.stringify(nb));\n });\n // PUT /api/contents/{path} - Save or upload a file\n app.router.put('/api/contents/(.+)', async (req, filename) => {\n const body = req.body;\n const nb = await contents.save(filename, body);\n return new Response(JSON.stringify(nb));\n });\n // DELETE /api/contents/{path} - Delete a file in the given path\n app.router.delete('/api/contents/(.+)', async (req, filename) => {\n await contents.delete(filename);\n return new Response(null, { status: 204 });\n });\n },\n};\n/**\n * A plugin installing the service worker.\n */\nconst serviceWorkerPlugin = {\n id: '@jupyterlite/server-extension:service-worker',\n autoStart: true,\n provides: IServiceWorkerManager,\n activate: (app) => {\n return new ServiceWorkerManager();\n },\n};\n/**\n * A plugin for handling communication with the Emscpriten file system.\n */\nconst emscriptenFileSystemPlugin = {\n id: '@jupyterlite/server-extension:emscripten-filesystem',\n autoStart: true,\n optional: [IServiceWorkerManager],\n provides: IBroadcastChannelWrapper,\n activate: (app, serviceWorkerRegistrationWrapper) => {\n const { contents } = app.serviceManager;\n const broadcaster = new BroadcastChannelWrapper({ contents });\n const what = 'Kernel filesystem and JupyterLite contents';\n function logStatus(msg, err) {\n if (err) {\n console.warn(err);\n }\n if (msg) {\n console.warn(msg);\n }\n if (err || msg) {\n console.warn(`${what} will NOT be synced`);\n }\n else {\n console.info(`${what} will be synced`);\n }\n }\n if (!serviceWorkerRegistrationWrapper) {\n logStatus('JupyterLite ServiceWorker not available');\n }\n else {\n serviceWorkerRegistrationWrapper.ready\n .then(() => {\n broadcaster.enable();\n logStatus();\n })\n .catch((err) => {\n logStatus('JupyterLite ServiceWorker failed to become available', err);\n });\n }\n return broadcaster;\n },\n};\n/**\n * The kernels service plugin.\n */\nconst kernelsPlugin = {\n id: '@jupyterlite/server-extension:kernels',\n autoStart: true,\n provides: IKernels,\n requires: [IKernelSpecs],\n activate: (app, kernelspecs) => {\n return new Kernels({ kernelspecs });\n },\n};\n/**\n * A plugin providing the routes for the kernels service\n */\nconst kernelsRoutesPlugin = {\n id: '@jupyterlite/server-extension:kernels-routes',\n autoStart: true,\n requires: [IKernels],\n activate: (app, kernels) => {\n // GET /api/kernels - List the running kernels\n app.router.get('/api/kernels', async (req) => {\n const res = await kernels.list();\n return new Response(JSON.stringify(res));\n });\n // POST /api/kernels/{kernel_id} - Restart a kernel\n app.router.post('/api/kernels/(.*)/restart', async (req, kernelId) => {\n const res = await kernels.restart(kernelId);\n return new Response(JSON.stringify(res));\n });\n // DELETE /api/kernels/{kernel_id} - Kill a kernel and delete the kernel id\n app.router.delete('/api/kernels/(.*)', async (req, kernelId) => {\n const res = await kernels.shutdown(kernelId);\n return new Response(JSON.stringify(res), { status: 204 });\n });\n },\n};\n/**\n * The kernel spec service plugin.\n */\nconst kernelSpecPlugin = {\n id: '@jupyterlite/server-extension:kernelspec',\n autoStart: true,\n provides: IKernelSpecs,\n activate: (app) => {\n return new KernelSpecs();\n },\n};\n/**\n * A plugin providing the routes for the kernelspec service.\n */\nconst kernelSpecRoutesPlugin = {\n id: '@jupyterlite/server-extension:kernelspec-routes',\n autoStart: true,\n requires: [IKernelSpecs],\n activate: (app, kernelspecs) => {\n app.router.get('/api/kernelspecs', async (req) => {\n const { specs } = kernelspecs;\n if (!specs) {\n return new Response(null);\n }\n // follow the same format as in Jupyter Server\n const allKernelSpecs = {};\n const allSpecs = specs.kernelspecs;\n Object.keys(allSpecs).forEach((name) => {\n const spec = allSpecs[name];\n const { resources } = spec !== null && spec !== void 0 ? spec : {};\n allKernelSpecs[name] = {\n name,\n spec,\n resources,\n };\n });\n const res = {\n default: specs.default,\n kernelspecs: allKernelSpecs,\n };\n return new Response(JSON.stringify(res));\n });\n },\n};\n/**\n * The licenses service plugin\n */\nconst licensesPlugin = {\n id: '@jupyterlite/server-extension:licenses',\n autoStart: true,\n provides: ILicenses,\n activate: (app) => {\n return new Licenses();\n },\n};\n/**\n * A plugin providing the routes for the licenses service.\n */\nconst licensesRoutesPlugin = {\n id: '@jupyterlite/server-extension:licenses-routes',\n autoStart: true,\n requires: [ILicenses],\n activate(app, licenses) {\n app.router.get('/api/licenses', async (req) => {\n const res = await licenses.get();\n return new Response(JSON.stringify(res));\n });\n },\n};\n/**\n * A plugin providing the routes for the lsp service.\n * TODO: provide the service in a separate plugin?\n */\nconst lspRoutesPlugin = {\n id: '@jupyterlite/server-extension:lsp-routes',\n autoStart: true,\n activate: (app) => {\n app.router.get('/lsp/status', async (req) => {\n return new Response(JSON.stringify({ version: 2, sessions: {}, specs: {} }));\n });\n },\n};\n/**\n * A plugin providing the routes for the nbconvert service.\n * TODO: provide the service in a separate plugin?\n */\nconst nbconvertRoutesPlugin = {\n id: '@jupyterlite/server-extension:nbconvert-routes',\n autoStart: true,\n activate: (app) => {\n app.router.get('/api/nbconvert', async (req) => {\n return new Response(JSON.stringify({}));\n });\n },\n};\n/**\n * The sessions service plugin.\n */\nconst sessionsPlugin = {\n id: '@jupyterlite/server-extension:sessions',\n autoStart: true,\n provides: ISessions,\n requires: [IKernels],\n activate: (app, kernels) => {\n return new Sessions({ kernels });\n },\n};\n/**\n * A plugin providing the routes for the session service.\n */\nconst sessionsRoutesPlugin = {\n id: '@jupyterlite/server-extension:sessions-routes',\n autoStart: true,\n requires: [ISessions],\n activate: (app, sessions) => {\n // GET /api/sessions/{session} - Get session\n app.router.get('/api/sessions/(.+)', async (req, id) => {\n const session = await sessions.get(id);\n return new Response(JSON.stringify(session), { status: 200 });\n });\n // GET /api/sessions - List available sessions\n app.router.get('/api/sessions', async (req) => {\n const list = await sessions.list();\n return new Response(JSON.stringify(list), { status: 200 });\n });\n // PATCH /api/sessions/{session} - This can be used to rename a session\n app.router.patch('/api/sessions(.*)', async (req, id) => {\n const options = req.body;\n const session = await sessions.patch(options);\n return new Response(JSON.stringify(session), { status: 200 });\n });\n // DELETE /api/sessions/{session} - Delete a session\n app.router.delete('/api/sessions/(.+)', async (req, id) => {\n await sessions.shutdown(id);\n return new Response(null, { status: 204 });\n });\n // POST /api/sessions - Create a new session or return an existing session if a session of the same name already exists\n app.router.post('/api/sessions', async (req) => {\n const options = req.body;\n const session = await sessions.startNew(options);\n return new Response(JSON.stringify(session), { status: 201 });\n });\n },\n};\n/**\n * The settings service plugin.\n */\nconst settingsPlugin = {\n id: '@jupyterlite/server-extension:settings',\n autoStart: true,\n requires: [ILocalForage],\n provides: ISettings,\n activate: (app, forage) => {\n const storageName = PageConfig.getOption('settingsStorageName');\n const storageDrivers = JSON.parse(PageConfig.getOption('settingsStorageDrivers') || 'null');\n const { localforage } = forage;\n const settings = new Settings({ storageName, storageDrivers, localforage });\n app.started.then(() => settings.initialize().catch(console.warn));\n return settings;\n },\n};\n/**\n * A plugin providing the routes for the settings service.\n */\nconst settingsRoutesPlugin = {\n id: '@jupyterlite/server-extension:settings-routes',\n autoStart: true,\n requires: [ISettings],\n activate: (app, settings) => {\n // TODO: improve the regex\n // const pluginPattern = new RegExp(/(?:@([^/]+?)[/])?([^/]+?):(\\w+)/);\n const pluginPattern = '/api/settings/((?:@([^/]+?)[/])?([^/]+?):([^:]+))$';\n app.router.get(pluginPattern, async (req, pluginId) => {\n const setting = await settings.get(pluginId);\n return new Response(JSON.stringify(setting));\n });\n app.router.put(pluginPattern, async (req, pluginId) => {\n const body = req.body;\n const { raw } = body;\n await settings.save(pluginId, raw);\n return new Response(null, { status: 204 });\n });\n app.router.get('/api/settings', async (req) => {\n const plugins = await settings.getAll();\n return new Response(JSON.stringify(plugins));\n });\n },\n};\n/**\n * The translation service plugin.\n */\nconst translationPlugin = {\n id: '@jupyterlite/server-extension:translation',\n autoStart: true,\n provides: ITranslation,\n activate: (app) => {\n const translation = new Translation();\n app.router.get('/api/translations/?(.*)', async (req, locale) => {\n if (locale === 'default') {\n locale = 'en';\n }\n const data = await translation.get(locale || 'all');\n return new Response(JSON.stringify(data));\n });\n return translation;\n },\n};\n/**\n * A plugin providing the routes for the translation service.\n */\nconst translationRoutesPlugin = {\n id: '@jupyterlite/server-extension:translation-routes',\n autoStart: true,\n requires: [ITranslation],\n activate: (app, translation) => {\n app.router.get('/api/translations/?(.*)', async (req, locale) => {\n const data = await translation.get(locale || 'all');\n return new Response(JSON.stringify(data));\n });\n },\n};\nconst plugins = [\n contentsPlugin,\n contentsRoutesPlugin,\n emscriptenFileSystemPlugin,\n kernelsPlugin,\n kernelsRoutesPlugin,\n kernelSpecPlugin,\n kernelSpecRoutesPlugin,\n licensesPlugin,\n licensesRoutesPlugin,\n localforageMemoryPlugin,\n localforagePlugin,\n lspRoutesPlugin,\n nbconvertRoutesPlugin,\n serviceWorkerPlugin,\n sessionsPlugin,\n sessionsRoutesPlugin,\n settingsPlugin,\n settingsRoutesPlugin,\n translationPlugin,\n translationRoutesPlugin,\n];\nexport default plugins;\n//# sourceMappingURL=index.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport memoryStorageDriver from 'localforage-memoryStorageDriver';\n/**\n * Ensure a localforage singleton has had the memory storage driver installed\n */\nexport async function ensureMemoryStorage(theLocalforage) {\n return await theLocalforage.defineDriver(memoryStorageDriver);\n}\n//# sourceMappingURL=memory.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2019, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for clipboard related functionality.\n */\nvar ClipboardExt;\n(function (ClipboardExt) {\n /**\n * Copy text to the system clipboard.\n *\n * @param text - The text to copy to the clipboard.\n */\n function copyText(text) {\n // Fetch the document body.\n const body = document.body;\n // Set up the clipboard event listener.\n const handler = (event) => {\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Set the clipboard data.\n event.clipboardData.setData('text', text);\n // Remove the event listener.\n body.removeEventListener('copy', handler, true);\n };\n // Add the event listener.\n body.addEventListener('copy', handler, true);\n // Trigger the event.\n document.execCommand('copy');\n }\n ClipboardExt.copyText = copyText;\n})(ClipboardExt || (ClipboardExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for element related utilities.\n */\nvar ElementExt;\n(function (ElementExt) {\n /**\n * Compute the box sizing for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The box sizing data for the specified element.\n */\n function boxSizing(element) {\n let style = window.getComputedStyle(element);\n let bt = parseFloat(style.borderTopWidth) || 0;\n let bl = parseFloat(style.borderLeftWidth) || 0;\n let br = parseFloat(style.borderRightWidth) || 0;\n let bb = parseFloat(style.borderBottomWidth) || 0;\n let pt = parseFloat(style.paddingTop) || 0;\n let pl = parseFloat(style.paddingLeft) || 0;\n let pr = parseFloat(style.paddingRight) || 0;\n let pb = parseFloat(style.paddingBottom) || 0;\n let hs = bl + pl + pr + br;\n let vs = bt + pt + pb + bb;\n return {\n borderTop: bt,\n borderLeft: bl,\n borderRight: br,\n borderBottom: bb,\n paddingTop: pt,\n paddingLeft: pl,\n paddingRight: pr,\n paddingBottom: pb,\n horizontalSum: hs,\n verticalSum: vs\n };\n }\n ElementExt.boxSizing = boxSizing;\n /**\n * Compute the size limits for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The size limit data for the specified element.\n */\n function sizeLimits(element) {\n let style = window.getComputedStyle(element);\n let minWidth = parseFloat(style.minWidth) || 0;\n let minHeight = parseFloat(style.minHeight) || 0;\n let maxWidth = parseFloat(style.maxWidth) || Infinity;\n let maxHeight = parseFloat(style.maxHeight) || Infinity;\n maxWidth = Math.max(minWidth, maxWidth);\n maxHeight = Math.max(minHeight, maxHeight);\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n ElementExt.sizeLimits = sizeLimits;\n /**\n * Test whether a client position lies within an element.\n *\n * @param element - The DOM element of interest.\n *\n * @param clientX - The client X coordinate of interest.\n *\n * @param clientY - The client Y coordinate of interest.\n *\n * @returns Whether the point is within the given element.\n */\n function hitTest(element, clientX, clientY) {\n let rect = element.getBoundingClientRect();\n return (clientX >= rect.left &&\n clientX < rect.right &&\n clientY >= rect.top &&\n clientY < rect.bottom);\n }\n ElementExt.hitTest = hitTest;\n /**\n * Vertically scroll an element into view if needed.\n *\n * @param area - The scroll area element.\n *\n * @param element - The element of interest.\n *\n * #### Notes\n * This follows the \"nearest\" behavior of the native `scrollIntoView`\n * method, which is not supported by all browsers.\n * https://drafts.csswg.org/cssom-view/#element-scrolling-members\n *\n * If the element fully covers the visible area or is fully contained\n * within the visible area, no scrolling will take place. Otherwise,\n * the nearest edges of the area and element are aligned.\n */\n function scrollIntoViewIfNeeded(area, element) {\n let ar = area.getBoundingClientRect();\n let er = element.getBoundingClientRect();\n if (er.top <= ar.top && er.bottom >= ar.bottom) {\n return;\n }\n if (er.top < ar.top && er.height <= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.bottom > ar.bottom && er.height >= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.top < ar.top && er.height > ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n if (er.bottom > ar.bottom && er.height < ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n }\n ElementExt.scrollIntoViewIfNeeded = scrollIntoViewIfNeeded;\n})(ElementExt || (ElementExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for platform related utilities.\n */\nvar Platform;\n(function (Platform) {\n /**\n * A flag indicating whether the platform is Mac.\n */\n Platform.IS_MAC = !!navigator.platform.match(/Mac/i);\n /**\n * A flag indicating whether the platform is Windows.\n */\n Platform.IS_WIN = !!navigator.platform.match(/Win/i);\n /**\n * A flag indicating whether the browser is IE.\n */\n Platform.IS_IE = /Trident/.test(navigator.userAgent);\n /**\n * A flag indicating whether the browser is Edge.\n */\n Platform.IS_EDGE = /Edge/.test(navigator.userAgent);\n /**\n * Test whether the `accel` key is pressed.\n *\n * @param event - The keyboard or mouse event of interest.\n *\n * @returns Whether the `accel` key is pressed.\n *\n * #### Notes\n * On Mac the `accel` key is the command key. On all other\n * platforms the `accel` key is the control key.\n */\n function accelKey(event) {\n return Platform.IS_MAC ? event.metaKey : event.ctrlKey;\n }\n Platform.accelKey = accelKey;\n})(Platform || (Platform = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for selector related utilities.\n */\nvar Selector;\n(function (Selector) {\n /**\n * Calculate the specificity of a single CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns The specificity of the selector.\n *\n * #### Undefined Behavior\n * The selector is invalid.\n *\n * #### Notes\n * This is based on https://www.w3.org/TR/css3-selectors/#specificity\n *\n * A larger number represents a more specific selector.\n *\n * The smallest possible specificity is `0`.\n *\n * The result is represented as a hex number `0x` where\n * each component is the count of the respective selector clause.\n *\n * If the selector contains commas, only the first clause is used.\n *\n * The computed result is cached, so subsequent calculations for the\n * same selector are extremely fast.\n */\n function calculateSpecificity(selector) {\n if (selector in Private.specificityCache) {\n return Private.specificityCache[selector];\n }\n let result = Private.calculateSingle(selector);\n return (Private.specificityCache[selector] = result);\n }\n Selector.calculateSpecificity = calculateSpecificity;\n /**\n * Test whether a selector is a valid CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns `true` if the selector is valid, `false` otherwise.\n *\n * #### Notes\n * The computed result is cached, so subsequent tests for the same\n * selector are extremely fast.\n */\n function isValid(selector) {\n if (selector in Private.validityCache) {\n return Private.validityCache[selector];\n }\n let result = true;\n try {\n Private.testElem.querySelector(selector);\n }\n catch (err) {\n result = false;\n }\n return (Private.validityCache[selector] = result);\n }\n Selector.isValid = isValid;\n /**\n * Test whether an element matches a CSS selector.\n *\n * @param element - The element of interest.\n *\n * @param selector - The valid CSS selector of interest.\n *\n * @returns `true` if the element is a match, `false` otherwise.\n *\n * #### Notes\n * This function uses the builtin browser capabilities when possible,\n * falling back onto a document query otherwise.\n */\n function matches(element, selector) {\n return Private.protoMatchFunc.call(element, selector);\n }\n Selector.matches = matches;\n})(Selector || (Selector = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A cache of computed selector specificity values.\n */\n Private.specificityCache = Object.create(null);\n /**\n * A cache of computed selector validity.\n */\n Private.validityCache = Object.create(null);\n /**\n * An empty element for testing selector validity.\n */\n Private.testElem = document.createElement('div');\n /**\n * A cross-browser CSS selector matching prototype function.\n */\n Private.protoMatchFunc = (() => {\n let proto = Element.prototype;\n return (proto.matches ||\n proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector ||\n function (selector) {\n let elem = this;\n let matches = elem.ownerDocument\n ? elem.ownerDocument.querySelectorAll(selector)\n : [];\n return Array.prototype.indexOf.call(matches, elem) !== -1;\n });\n })();\n /**\n * Calculate the specificity of a single selector.\n *\n * The behavior is undefined if the selector is invalid.\n */\n function calculateSingle(selector) {\n // Ignore anything after the first comma.\n selector = selector.split(',', 1)[0];\n // Setup the aggregate counters.\n let a = 0;\n let b = 0;\n let c = 0;\n // Apply a regex to the front of the selector. If it succeeds, that\n // portion of the selector is removed. Returns a success/fail flag.\n function match(re) {\n let match = selector.match(re);\n if (match === null) {\n return false;\n }\n selector = selector.slice(match[0].length);\n return true;\n }\n // Replace the negation pseudo-class (which is ignored),\n // but keep its inner content (which is not ignored).\n selector = selector.replace(NEGATION_RE, ' $1 ');\n // Continue matching until the selector is consumed.\n while (selector.length > 0) {\n // Match an ID selector.\n if (match(ID_RE)) {\n a++;\n continue;\n }\n // Match a class selector.\n if (match(CLASS_RE)) {\n b++;\n continue;\n }\n // Match an attribute selector.\n if (match(ATTR_RE)) {\n b++;\n continue;\n }\n // Match a pseudo-element selector. This is done before matching\n // a pseudo-class since this regex overlaps with that regex.\n if (match(PSEUDO_ELEM_RE)) {\n c++;\n continue;\n }\n // Match a pseudo-class selector.\n if (match(PSEDUO_CLASS_RE)) {\n b++;\n continue;\n }\n // Match a plain type selector.\n if (match(TYPE_RE)) {\n c++;\n continue;\n }\n // Finally, match any ignored characters.\n if (match(IGNORE_RE)) {\n continue;\n }\n // At this point, the selector is assumed to be invalid.\n return 0;\n }\n // Clamp each component to a reasonable base.\n a = Math.min(a, 0xff);\n b = Math.min(b, 0xff);\n c = Math.min(c, 0xff);\n // Combine the components into a single result.\n return (a << 16) | (b << 8) | c;\n }\n Private.calculateSingle = calculateSingle;\n /**\n * A regex which matches an ID selector at string start.\n */\n const ID_RE = /^#[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a class selector at string start.\n */\n const CLASS_RE = /^\\.[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches an attribute selector at string start.\n */\n const ATTR_RE = /^\\[[^\\]]+\\]/;\n /**\n * A regex which matches a type selector at string start.\n */\n const TYPE_RE = /^[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a pseudo-element selector at string start.\n */\n const PSEUDO_ELEM_RE = /^(::[^\\s\\+>~#\\.\\[:]+|:first-line|:first-letter|:before|:after)/;\n /**\n * A regex which matches a pseudo-class selector at string start.\n */\n const PSEDUO_CLASS_RE = /^:[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches ignored characters at string start.\n */\n const IGNORE_RE = /^[\\s\\+>~\\*]+/;\n /**\n * A regex which matches the negation pseudo-class globally.\n */\n const NEGATION_RE = /:not\\(([^\\)]+)\\)/g;\n})(Private || (Private = {}));\n\nexport { ClipboardExt, ElementExt, Platform, Selector };\n//# sourceMappingURL=index.es6.js.map\n","import { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\n/**\n * A disposable object which delegates to a callback function.\n */\nclass DisposableDelegate {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn) {\n this._fn = fn;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return !this._fn;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n}\n/**\n * An observable disposable object which delegates to a callback function.\n */\nclass ObservableDisposableDelegate extends DisposableDelegate {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * An object which manages a collection of disposable items.\n */\nclass DisposableSet {\n constructor() {\n this._isDisposed = false;\n this._items = new Set();\n }\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item) {\n return this._items.has(item);\n }\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item) {\n this._items.add(item);\n }\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item) {\n this._items.delete(item);\n }\n /**\n * Remove all items from the set.\n */\n clear() {\n this._items.clear();\n }\n}\n/**\n * The namespace for the `DisposableSet` class statics.\n */\n(function (DisposableSet) {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n DisposableSet.from = from;\n})(DisposableSet || (DisposableSet = {}));\n/**\n * An observable object which manages a collection of disposable items.\n */\nclass ObservableDisposableSet extends DisposableSet {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\n(function (ObservableDisposableSet) {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n ObservableDisposableSet.from = from;\n})(ObservableDisposableSet || (ObservableDisposableSet = {}));\n\nexport { DisposableDelegate, DisposableSet, ObservableDisposableDelegate, ObservableDisposableSet };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module keyboard\n */\n/**\n * Get the global application keyboard layout instance.\n *\n * @returns The keyboard layout for use by the application.\n *\n * #### Notes\n * The default keyboard layout is US-English.\n */\nfunction getKeyboardLayout() {\n return Private.keyboardLayout;\n}\n/**\n * Set the global application keyboard layout instance.\n *\n * @param - The keyboard layout for use by the application.\n *\n * #### Notes\n * The keyboard layout should typically be set on application startup\n * to a layout which is appropriate for the user's system.\n */\nfunction setKeyboardLayout(layout) {\n Private.keyboardLayout = layout;\n}\n/**\n * A concrete implementation of {@link IKeyboardLayout} based on keycodes.\n *\n * The `keyCode` property of a `'keydown'` event is a browser and OS\n * specific representation of the physical key (not character) which\n * was pressed on a keyboard. While not the most convenient API, it\n * is currently the only one which works reliably on all browsers.\n *\n * This class accepts a user-defined mapping of keycode to key, which\n * allows for reliable shortcuts tailored to the user's system.\n */\nclass KeycodeLayout {\n /**\n * Construct a new keycode layout.\n *\n * @param name - The human readable name for the layout.\n *\n * @param codes - A mapping of keycode to key value.\n *\n * @param modifierKeys - Array of modifier key names\n */\n constructor(name, codes, modifierKeys = []) {\n this.name = name;\n this._codes = codes;\n this._keys = KeycodeLayout.extractKeys(codes);\n this._modifierKeys = KeycodeLayout.convertToKeySet(modifierKeys);\n }\n /**\n * Get an array of the key values supported by the layout.\n *\n * @returns A new array of the supported key values.\n */\n keys() {\n return Object.keys(this._keys);\n }\n /**\n * Test whether the given key is a valid value for the layout.\n *\n * @param key - The user provided key to test for validity.\n *\n * @returns `true` if the key is valid, `false` otherwise.\n */\n isValidKey(key) {\n return key in this._keys;\n }\n /**\n * Test whether the given key is a modifier key.\n *\n * @param key - The user provided key.\n *\n * @returns `true` if the key is a modifier key, `false` otherwise.\n */\n isModifierKey(key) {\n return key in this._modifierKeys;\n }\n /**\n * Get the key for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns The associated key value, or an empty string if\n * the event does not represent a valid primary key.\n */\n keyForKeydownEvent(event) {\n return this._codes[event.keyCode] || '';\n }\n}\n/**\n * The namespace for the `KeycodeLayout` class statics.\n */\n(function (KeycodeLayout) {\n /**\n * Extract the set of keys from a code map.\n *\n * @param code - The code map of interest.\n *\n * @returns A set of the keys in the code map.\n */\n function extractKeys(codes) {\n let keys = Object.create(null);\n for (let c in codes) {\n keys[codes[c]] = true;\n }\n return keys;\n }\n KeycodeLayout.extractKeys = extractKeys;\n /**\n * Convert array of keys to a key set.\n *\n * @param keys - The array that needs to be converted\n *\n * @returns A set of the keys in the array.\n */\n function convertToKeySet(keys) {\n let keySet = Object(null);\n for (let i = 0, n = keys.length; i < n; ++i) {\n keySet[keys[i]] = true;\n }\n return keySet;\n }\n KeycodeLayout.convertToKeySet = convertToKeySet;\n})(KeycodeLayout || (KeycodeLayout = {}));\n/**\n * A keycode-based keyboard layout for US English keyboards.\n *\n * This layout is valid for the following OS/Browser combinations.\n *\n * - Windows\n * - Chrome\n * - Firefox\n * - IE\n *\n * - OSX\n * - Chrome\n * - Firefox\n * - Safari\n *\n * - Linux\n * - Chrome\n * - Firefox\n *\n * Other combinations may also work, but are untested.\n */\nconst EN_US = new KeycodeLayout('en-us', {\n 8: 'Backspace',\n 9: 'Tab',\n 13: 'Enter',\n 16: 'Shift',\n 17: 'Ctrl',\n 18: 'Alt',\n 19: 'Pause',\n 27: 'Escape',\n 32: 'Space',\n 33: 'PageUp',\n 34: 'PageDown',\n 35: 'End',\n 36: 'Home',\n 37: 'ArrowLeft',\n 38: 'ArrowUp',\n 39: 'ArrowRight',\n 40: 'ArrowDown',\n 45: 'Insert',\n 46: 'Delete',\n 48: '0',\n 49: '1',\n 50: '2',\n 51: '3',\n 52: '4',\n 53: '5',\n 54: '6',\n 55: '7',\n 56: '8',\n 57: '9',\n 59: ';',\n 61: '=',\n 65: 'A',\n 66: 'B',\n 67: 'C',\n 68: 'D',\n 69: 'E',\n 70: 'F',\n 71: 'G',\n 72: 'H',\n 73: 'I',\n 74: 'J',\n 75: 'K',\n 76: 'L',\n 77: 'M',\n 78: 'N',\n 79: 'O',\n 80: 'P',\n 81: 'Q',\n 82: 'R',\n 83: 'S',\n 84: 'T',\n 85: 'U',\n 86: 'V',\n 87: 'W',\n 88: 'X',\n 89: 'Y',\n 90: 'Z',\n 91: 'Meta',\n 93: 'ContextMenu',\n 96: '0',\n 97: '1',\n 98: '2',\n 99: '3',\n 100: '4',\n 101: '5',\n 102: '6',\n 103: '7',\n 104: '8',\n 105: '9',\n 106: '*',\n 107: '+',\n 109: '-',\n 110: '.',\n 111: '/',\n 112: 'F1',\n 113: 'F2',\n 114: 'F3',\n 115: 'F4',\n 116: 'F5',\n 117: 'F6',\n 118: 'F7',\n 119: 'F8',\n 120: 'F9',\n 121: 'F10',\n 122: 'F11',\n 123: 'F12',\n 173: '-',\n 186: ';',\n 187: '=',\n 188: ',',\n 189: '-',\n 190: '.',\n 191: '/',\n 192: '`',\n 219: '[',\n 220: '\\\\',\n 221: ']',\n 222: \"'\",\n 224: 'Meta' // firefox\n}, ['Shift', 'Ctrl', 'Alt', 'Meta'] // modifier keys\n);\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The global keyboard layout instance.\n */\n Private.keyboardLayout = EN_US;\n})(Private || (Private = {}));\n\nexport { EN_US, KeycodeLayout, getKeyboardLayout, setKeyboardLayout };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt } from '@lumino/algorithm';\nimport { JSONExt } from '@lumino/coreutils';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport { Platform, Selector } from '@lumino/domutils';\nimport { getKeyboardLayout } from '@lumino/keyboard';\nimport { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module commands\n */\n/**\n * An object which manages a collection of commands.\n *\n * #### Notes\n * A command registry can be used to populate a variety of action-based\n * widgets, such as command palettes, menus, and toolbars.\n */\nclass CommandRegistry {\n constructor() {\n this._timerID = 0;\n this._replaying = false;\n this._keystrokes = [];\n this._keydownEvents = [];\n this._keyBindings = [];\n this._exactKeyMatch = null;\n this._commands = new Map();\n this._commandChanged = new Signal(this);\n this._commandExecuted = new Signal(this);\n this._keyBindingChanged = new Signal(this);\n }\n /**\n * A signal emitted when a command has changed.\n *\n * #### Notes\n * This signal is useful for visual representations of commands which\n * need to refresh when the state of a relevant command has changed.\n */\n get commandChanged() {\n return this._commandChanged;\n }\n /**\n * A signal emitted when a command has executed.\n *\n * #### Notes\n * Care should be taken when consuming this signal. The command system is used\n * by many components for many user actions. Handlers registered with this\n * signal must return quickly to ensure the overall application remains responsive.\n */\n get commandExecuted() {\n return this._commandExecuted;\n }\n /**\n * A signal emitted when a key binding is changed.\n */\n get keyBindingChanged() {\n return this._keyBindingChanged;\n }\n /**\n * A read-only array of the key bindings in the registry.\n */\n get keyBindings() {\n return this._keyBindings;\n }\n /**\n * List the ids of the registered commands.\n *\n * @returns A new array of the registered command ids.\n */\n listCommands() {\n return Array.from(this._commands.keys());\n }\n /**\n * Test whether a specific command is registered.\n *\n * @param id - The id of the command of interest.\n *\n * @returns `true` if the command is registered, `false` otherwise.\n */\n hasCommand(id) {\n return this._commands.has(id);\n }\n /**\n * Add a command to the registry.\n *\n * @param id - The unique id of the command.\n *\n * @param options - The options for the command.\n *\n * @returns A disposable which will remove the command.\n *\n * @throws An error if the given `id` is already registered.\n */\n addCommand(id, options) {\n // Throw an error if the id is already registered.\n if (this._commands.has(id)) {\n throw new Error(`Command '${id}' already registered.`);\n }\n // Add the command to the registry.\n this._commands.set(id, Private.createCommand(options));\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'added' });\n // Return a disposable which will remove the command.\n return new DisposableDelegate(() => {\n // Remove the command from the registry.\n this._commands.delete(id);\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'removed' });\n });\n }\n /**\n * Notify listeners that the state of a command has changed.\n *\n * @param id - The id of the command which has changed. If more than\n * one command has changed, this argument should be omitted.\n *\n * @throws An error if the given `id` is not registered.\n *\n * #### Notes\n * This method should be called by the command author whenever the\n * application state changes such that the results of the command\n * metadata functions may have changed.\n *\n * This will cause the `commandChanged` signal to be emitted.\n */\n notifyCommandChanged(id) {\n if (id !== undefined && !this._commands.has(id)) {\n throw new Error(`Command '${id}' is not registered.`);\n }\n this._commandChanged.emit({ id, type: id ? 'changed' : 'many-changed' });\n }\n /**\n * Get the description for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The description for the command.\n */\n describedBy(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return Promise.resolve((_a = cmd === null || cmd === void 0 ? void 0 : cmd.describedBy.call(undefined, args)) !== null && _a !== void 0 ? _a : { args: null });\n }\n /**\n * Get the display label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The display label for the command, or an empty string\n * if the command is not registered.\n */\n label(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return (_a = cmd === null || cmd === void 0 ? void 0 : cmd.label.call(undefined, args)) !== null && _a !== void 0 ? _a : '';\n }\n /**\n * Get the mnemonic index for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The mnemonic index for the command, or `-1` if the\n * command is not registered.\n */\n mnemonic(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.mnemonic.call(undefined, args) : -1;\n }\n /**\n * Get the icon renderer for a specific command.\n *\n * DEPRECATED: if set to a string value, the .icon field will\n * function as an alias for the .iconClass field, for backwards\n * compatibility. In the future when this is removed, the default\n * return type will become undefined.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon renderer for the command or `undefined`.\n */\n icon(id, args = JSONExt.emptyObject) {\n var _a;\n return (_a = this._commands.get(id)) === null || _a === void 0 ? void 0 : _a.icon.call(undefined, args);\n }\n /**\n * Get the icon class for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon class for the command, or an empty string if\n * the command is not registered.\n */\n iconClass(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconClass.call(undefined, args) : '';\n }\n /**\n * Get the icon label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon label for the command, or an empty string if\n * the command is not registered.\n */\n iconLabel(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconLabel.call(undefined, args) : '';\n }\n /**\n * Get the short form caption for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The caption for the command, or an empty string if the\n * command is not registered.\n */\n caption(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.caption.call(undefined, args) : '';\n }\n /**\n * Get the usage help text for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The usage text for the command, or an empty string if\n * the command is not registered.\n */\n usage(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.usage.call(undefined, args) : '';\n }\n /**\n * Get the extra class name for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The class name for the command, or an empty string if\n * the command is not registered.\n */\n className(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.className.call(undefined, args) : '';\n }\n /**\n * Get the dataset for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The dataset for the command, or an empty dataset if\n * the command is not registered.\n */\n dataset(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.dataset.call(undefined, args) : {};\n }\n /**\n * Test whether a specific command is enabled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is enabled,\n * or `false` if the command is not registered.\n */\n isEnabled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isEnabled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggled,\n * or `false` if the command is not registered.\n */\n isToggled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggleable.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggleable,\n * or `false` if the command is not registered.\n */\n isToggleable(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggleable : false;\n }\n /**\n * Test whether a specific command is visible.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is visible,\n * or `false` if the command is not registered.\n */\n isVisible(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isVisible.call(undefined, args) : false;\n }\n /**\n * Execute a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A promise which resolves with the result of the command.\n *\n * #### Notes\n * The promise will reject if the command throws an exception,\n * or if the command is not registered.\n */\n execute(id, args = JSONExt.emptyObject) {\n // Reject if the command is not registered.\n let cmd = this._commands.get(id);\n if (!cmd) {\n return Promise.reject(new Error(`Command '${id}' not registered.`));\n }\n // Execute the command and reject if an exception is thrown.\n let value;\n try {\n value = cmd.execute.call(undefined, args);\n }\n catch (err) {\n value = Promise.reject(err);\n }\n // Create the return promise which resolves the result.\n let result = Promise.resolve(value);\n // Emit the command executed signal.\n this._commandExecuted.emit({ id, args, result });\n // Return the result promise to the caller.\n return result;\n }\n /**\n * Add a key binding to the registry.\n *\n * @param options - The options for creating the key binding.\n *\n * @returns A disposable which removes the added key binding.\n *\n * #### Notes\n * If multiple key bindings are registered for the same sequence, the\n * binding with the highest selector specificity is executed first. A\n * tie is broken by using the most recently added key binding.\n *\n * Ambiguous key bindings are resolved with a timeout. As an example,\n * suppose two key bindings are registered: one with the key sequence\n * `['Ctrl D']`, and another with `['Ctrl D', 'Ctrl W']`. If the user\n * presses `Ctrl D`, the first binding cannot be immediately executed\n * since the user may intend to complete the chord with `Ctrl W`. For\n * such cases, a timer is used to allow the chord to be completed. If\n * the chord is not completed before the timeout, the first binding\n * is executed.\n */\n addKeyBinding(options) {\n // Create the binding for the given options.\n let binding = Private.createKeyBinding(options);\n // Add the key binding to the bindings array.\n this._keyBindings.push(binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'added' });\n // Return a disposable which will remove the binding.\n return new DisposableDelegate(() => {\n // Remove the binding from the array.\n ArrayExt.removeFirstOf(this._keyBindings, binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'removed' });\n });\n }\n /**\n * Process a `'keydown'` event and invoke a matching key binding.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * #### Notes\n * This should be called in response to a `'keydown'` event in order\n * to invoke the command for the best matching key binding.\n *\n * The registry **does not** install its own listener for `'keydown'`\n * events. This allows the application full control over the nodes\n * and phase for which the registry processes `'keydown'` events.\n *\n * When the keydown event is processed, if the event target or any of its\n * ancestor nodes has a `data-lm-suppress-shortcuts` attribute, its keydown\n * events will not invoke commands.\n */\n processKeydownEvent(event) {\n // Bail immediately if playing back keystrokes.\n if (this._replaying || CommandRegistry.isModifierKeyPressed(event)) {\n return;\n }\n // Get the normalized keystroke for the event.\n let keystroke = CommandRegistry.keystrokeForKeydownEvent(event);\n // If the keystroke is not valid for the keyboard layout, replay\n // any suppressed events and clear the pending state.\n if (!keystroke) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Add the keystroke to the current key sequence.\n this._keystrokes.push(keystroke);\n // Find the exact and partial matches for the key sequence.\n let { exact, partial } = Private.matchKeyBinding(this._keyBindings, this._keystrokes, event);\n // If there is no exact match and no partial match, replay\n // any suppressed events and clear the pending state.\n if (!exact && !partial) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Stop propagation of the event. If there is only a partial match,\n // the event will be replayed if a final exact match never occurs.\n event.preventDefault();\n event.stopPropagation();\n // If there is an exact match but no partial match, the exact match\n // can be dispatched immediately. The pending state is cleared so\n // the next key press starts from the default state.\n if (exact && !partial) {\n this._executeKeyBinding(exact);\n this._clearPendingState();\n return;\n }\n // If there is both an exact match and a partial match, the exact\n // match is stored for future dispatch in case the timer expires\n // before a more specific match is triggered.\n if (exact) {\n this._exactKeyMatch = exact;\n }\n // Store the event for possible playback in the future.\n this._keydownEvents.push(event);\n // (Re)start the timer to dispatch the most recent exact match\n // in case the partial match fails to result in an exact match.\n this._startTimer();\n }\n /**\n * Start or restart the pending timeout.\n */\n _startTimer() {\n this._clearTimer();\n this._timerID = window.setTimeout(() => {\n this._onPendingTimeout();\n }, Private.CHORD_TIMEOUT);\n }\n /**\n * Clear the pending timeout.\n */\n _clearTimer() {\n if (this._timerID !== 0) {\n clearTimeout(this._timerID);\n this._timerID = 0;\n }\n }\n /**\n * Replay the keydown events which were suppressed.\n */\n _replayKeydownEvents() {\n if (this._keydownEvents.length === 0) {\n return;\n }\n this._replaying = true;\n this._keydownEvents.forEach(Private.replayKeyEvent);\n this._replaying = false;\n }\n /**\n * Execute the command for the given key binding.\n *\n * If the command is missing or disabled, a warning will be logged.\n */\n _executeKeyBinding(binding) {\n let { command, args } = binding;\n let newArgs = {\n _luminoEvent: { type: 'keybinding', keys: binding.keys },\n ...args\n };\n if (!this.hasCommand(command) || !this.isEnabled(command, newArgs)) {\n let word = this.hasCommand(command) ? 'enabled' : 'registered';\n let keys = binding.keys.join(', ');\n let msg1 = `Cannot execute key binding '${keys}':`;\n let msg2 = `command '${command}' is not ${word}.`;\n console.warn(`${msg1} ${msg2}`);\n return;\n }\n this.execute(command, newArgs);\n }\n /**\n * Clear the internal pending state.\n */\n _clearPendingState() {\n this._clearTimer();\n this._exactKeyMatch = null;\n this._keystrokes.length = 0;\n this._keydownEvents.length = 0;\n }\n /**\n * Handle the partial match timeout.\n */\n _onPendingTimeout() {\n this._timerID = 0;\n if (this._exactKeyMatch) {\n this._executeKeyBinding(this._exactKeyMatch);\n }\n else {\n this._replayKeydownEvents();\n }\n this._clearPendingState();\n }\n}\n/**\n * The namespace for the `CommandRegistry` class statics.\n */\n(function (CommandRegistry) {\n /**\n * Parse a keystroke into its constituent components.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The parsed components of the keystroke.\n *\n * #### Notes\n * The keystroke should be of the form:\n * `[ [ [ ]]]`\n *\n * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and\n * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and\n * `Ctrl` on all other platforms.\n *\n * The parsing is tolerant and will not throw exceptions. Notably:\n * - Duplicate modifiers are ignored.\n * - Extra primary keys are ignored.\n * - The order of modifiers and primary key is irrelevant.\n * - The keystroke parts should be separated by whitespace.\n * - The keystroke is case sensitive.\n */\n function parseKeystroke(keystroke) {\n let key = '';\n let alt = false;\n let cmd = false;\n let ctrl = false;\n let shift = false;\n for (let token of keystroke.split(/\\s+/)) {\n if (token === 'Accel') {\n if (Platform.IS_MAC) {\n cmd = true;\n }\n else {\n ctrl = true;\n }\n }\n else if (token === 'Alt') {\n alt = true;\n }\n else if (token === 'Cmd') {\n cmd = true;\n }\n else if (token === 'Ctrl') {\n ctrl = true;\n }\n else if (token === 'Shift') {\n shift = true;\n }\n else if (token.length > 0) {\n key = token;\n }\n }\n return { cmd, ctrl, alt, shift, key };\n }\n CommandRegistry.parseKeystroke = parseKeystroke;\n /**\n * Normalize a keystroke into a canonical representation.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The normalized representation of the keystroke.\n *\n * #### Notes\n * This normalizes the keystroke by removing duplicate modifiers and\n * extra primary keys, and assembling the parts in a canonical order.\n *\n * The `Cmd` modifier is ignored on non-Mac platforms.\n */\n function normalizeKeystroke(keystroke) {\n let mods = '';\n let parts = parseKeystroke(keystroke);\n if (parts.ctrl) {\n mods += 'Ctrl ';\n }\n if (parts.alt) {\n mods += 'Alt ';\n }\n if (parts.shift) {\n mods += 'Shift ';\n }\n if (parts.cmd && Platform.IS_MAC) {\n mods += 'Cmd ';\n }\n return mods + parts.key;\n }\n CommandRegistry.normalizeKeystroke = normalizeKeystroke;\n /**\n * Get the platform-specific normalized keys for an options object.\n *\n * @param options - The options for the key binding.\n *\n * @returns Array of combined, normalized keys.\n */\n function normalizeKeys(options) {\n let keys;\n if (Platform.IS_WIN) {\n keys = options.winKeys || options.keys;\n }\n else if (Platform.IS_MAC) {\n keys = options.macKeys || options.keys;\n }\n else {\n keys = options.linuxKeys || options.keys;\n }\n return keys.map(normalizeKeystroke);\n }\n CommandRegistry.normalizeKeys = normalizeKeys;\n /**\n * Format keystrokes for display on the local system.\n *\n * If a list of keystrokes is provided, it will be displayed as\n * a comma-separated string\n *\n * @param keystroke The keystrokes to format\n * @returns The keystrokes representation\n */\n function formatKeystroke(keystroke) {\n return typeof keystroke === 'string'\n ? formatSingleKey(keystroke)\n : keystroke.map(formatSingleKey).join(', ');\n function formatSingleKey(key) {\n let mods = [];\n let separator = Platform.IS_MAC ? ' ' : '+';\n let parts = parseKeystroke(key);\n if (parts.ctrl) {\n mods.push('Ctrl');\n }\n if (parts.alt) {\n mods.push('Alt');\n }\n if (parts.shift) {\n mods.push('Shift');\n }\n if (Platform.IS_MAC && parts.cmd) {\n mods.push('Cmd');\n }\n mods.push(parts.key);\n return mods.map(Private.formatKey).join(separator);\n }\n }\n CommandRegistry.formatKeystroke = formatKeystroke;\n /**\n * Check if `'keydown'` event is caused by pressing a modifier key that should be ignored.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns `true` if modifier key was pressed, `false` otherwise.\n */\n function isModifierKeyPressed(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n return layout.isModifierKey(key);\n }\n CommandRegistry.isModifierKeyPressed = isModifierKeyPressed;\n /**\n * Create a normalized keystroke for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns A normalized keystroke, or an empty string if the event\n * does not represent a valid keystroke for the given layout.\n */\n function keystrokeForKeydownEvent(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n if (!key || layout.isModifierKey(key)) {\n return '';\n }\n let mods = [];\n if (event.ctrlKey) {\n mods.push('Ctrl');\n }\n if (event.altKey) {\n mods.push('Alt');\n }\n if (event.shiftKey) {\n mods.push('Shift');\n }\n if (event.metaKey && Platform.IS_MAC) {\n mods.push('Cmd');\n }\n mods.push(key);\n return mods.join(' ');\n }\n CommandRegistry.keystrokeForKeydownEvent = keystrokeForKeydownEvent;\n})(CommandRegistry || (CommandRegistry = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The timeout in ms for triggering a key binding chord.\n */\n Private.CHORD_TIMEOUT = 1000;\n /**\n * Create a normalized command from an options object.\n */\n function createCommand(options) {\n return {\n execute: options.execute,\n describedBy: asFunc(typeof options.describedBy === 'function'\n ? options.describedBy\n : { args: null, ...options.describedBy }, () => {\n return { args: null };\n }),\n label: asFunc(options.label, emptyStringFunc),\n mnemonic: asFunc(options.mnemonic, negativeOneFunc),\n icon: asFunc(options.icon, undefinedFunc),\n iconClass: asFunc(options.iconClass, emptyStringFunc),\n iconLabel: asFunc(options.iconLabel, emptyStringFunc),\n caption: asFunc(options.caption, emptyStringFunc),\n usage: asFunc(options.usage, emptyStringFunc),\n className: asFunc(options.className, emptyStringFunc),\n dataset: asFunc(options.dataset, emptyDatasetFunc),\n isEnabled: options.isEnabled || trueFunc,\n isToggled: options.isToggled || falseFunc,\n isToggleable: options.isToggleable || !!options.isToggled,\n isVisible: options.isVisible || trueFunc\n };\n }\n Private.createCommand = createCommand;\n /**\n * Create a key binding object from key binding options.\n */\n function createKeyBinding(options) {\n return {\n keys: CommandRegistry.normalizeKeys(options),\n selector: validateSelector(options),\n command: options.command,\n args: options.args || JSONExt.emptyObject\n };\n }\n Private.createKeyBinding = createKeyBinding;\n /**\n * Find the key bindings which match a key sequence.\n *\n * This returns a match result which contains the best exact matching\n * binding, and a flag which indicates if there are partial matches.\n */\n function matchKeyBinding(bindings, keys, event) {\n // The current best exact match.\n let exact = null;\n // Whether a partial match has been found.\n let partial = false;\n // The match distance for the exact match.\n let distance = Infinity;\n // The specificity for the exact match.\n let specificity = 0;\n // Iterate over the bindings and search for the best match.\n for (let i = 0, n = bindings.length; i < n; ++i) {\n // Lookup the current binding.\n let binding = bindings[i];\n // Check whether the key binding sequence is a match.\n let sqm = matchSequence(binding.keys, keys);\n // If there is no match, the binding is ignored.\n if (sqm === 0 /* SequenceMatch.None */) {\n continue;\n }\n // If it is a partial match and no other partial match has been\n // found, ensure the selector matches and set the partial flag.\n if (sqm === 2 /* SequenceMatch.Partial */) {\n if (!partial && targetDistance(binding.selector, event) !== -1) {\n partial = true;\n }\n continue;\n }\n // Ignore the match if the selector doesn't match, or if the\n // matched node is farther away than the current best match.\n let td = targetDistance(binding.selector, event);\n if (td === -1 || td > distance) {\n continue;\n }\n // Get the specificity for the selector.\n let sp = Selector.calculateSpecificity(binding.selector);\n // Update the best match if this match is stronger.\n if (!exact || td < distance || sp >= specificity) {\n exact = binding;\n distance = td;\n specificity = sp;\n }\n }\n // Return the match result.\n return { exact, partial };\n }\n Private.matchKeyBinding = matchKeyBinding;\n /**\n * Replay a keyboard event.\n *\n * This synthetically dispatches a clone of the keyboard event.\n */\n function replayKeyEvent(event) {\n event.target.dispatchEvent(cloneKeyboardEvent(event));\n }\n Private.replayKeyEvent = replayKeyEvent;\n function formatKey(key) {\n if (Platform.IS_MAC) {\n return MAC_DISPLAY.hasOwnProperty(key) ? MAC_DISPLAY[key] : key;\n }\n else {\n return WIN_DISPLAY.hasOwnProperty(key) ? WIN_DISPLAY[key] : key;\n }\n }\n Private.formatKey = formatKey;\n const MAC_DISPLAY = {\n Backspace: '⌫',\n Tab: '⇥',\n Enter: '⏎',\n Shift: '⇧',\n Ctrl: '⌃',\n Alt: '⌥',\n Escape: '⎋',\n PageUp: '⇞',\n PageDown: '⇟',\n End: '↘',\n Home: '↖',\n ArrowLeft: '←',\n ArrowUp: '↑',\n ArrowRight: '→',\n ArrowDown: '↓',\n Delete: '⌦',\n Cmd: '⌘'\n };\n const WIN_DISPLAY = {\n Escape: 'Esc',\n PageUp: 'Page Up',\n PageDown: 'Page Down',\n ArrowLeft: 'Left',\n ArrowUp: 'Up',\n ArrowRight: 'Right',\n ArrowDown: 'Down',\n Delete: 'Del'\n };\n /**\n * A singleton empty string function.\n */\n const emptyStringFunc = () => '';\n /**\n * A singleton `-1` number function\n */\n const negativeOneFunc = () => -1;\n /**\n * A singleton true boolean function.\n */\n const trueFunc = () => true;\n /**\n * A singleton false boolean function.\n */\n const falseFunc = () => false;\n /**\n * A singleton empty dataset function.\n */\n const emptyDatasetFunc = () => ({});\n /**\n * A singleton undefined function\n */\n const undefinedFunc = () => undefined;\n /**\n * Cast a value or command func to a command func.\n */\n function asFunc(value, dfault) {\n if (value === undefined) {\n return dfault;\n }\n if (typeof value === 'function') {\n return value;\n }\n return () => value;\n }\n /**\n * Validate the selector for an options object.\n *\n * This returns the validated selector, or throws if the selector is\n * invalid or contains commas.\n */\n function validateSelector(options) {\n if (options.selector.indexOf(',') !== -1) {\n throw new Error(`Selector cannot contain commas: ${options.selector}`);\n }\n if (!Selector.isValid(options.selector)) {\n throw new Error(`Invalid selector: ${options.selector}`);\n }\n return options.selector;\n }\n /**\n * Test whether a key binding sequence matches a key sequence.\n *\n * Returns a `SequenceMatch` value indicating the type of match.\n */\n function matchSequence(bindKeys, userKeys) {\n if (bindKeys.length < userKeys.length) {\n return 0 /* SequenceMatch.None */;\n }\n for (let i = 0, n = userKeys.length; i < n; ++i) {\n if (bindKeys[i] !== userKeys[i]) {\n return 0 /* SequenceMatch.None */;\n }\n }\n if (bindKeys.length > userKeys.length) {\n return 2 /* SequenceMatch.Partial */;\n }\n return 1 /* SequenceMatch.Exact */;\n }\n /**\n * Find the distance from the target node to the first matching node.\n *\n * This traverses the event path from `target` to `currentTarget` and\n * computes the distance from `target` to the first node which matches\n * the CSS selector. If no match is found, `-1` is returned.\n */\n function targetDistance(selector, event) {\n let targ = event.target;\n let curr = event.currentTarget;\n for (let dist = 0; targ !== null; targ = targ.parentElement, ++dist) {\n if (targ.hasAttribute('data-lm-suppress-shortcuts')) {\n return -1;\n }\n if (Selector.matches(targ, selector)) {\n return dist;\n }\n if (targ === curr) {\n return -1;\n }\n }\n return -1;\n }\n /**\n * Clone a keyboard event.\n */\n function cloneKeyboardEvent(event) {\n // A custom event is required because Chrome nulls out the\n // `keyCode` field in user-generated `KeyboardEvent` types.\n let clone = document.createEvent('Event');\n let bubbles = event.bubbles || true;\n let cancelable = event.cancelable || true;\n clone.initEvent(event.type || 'keydown', bubbles, cancelable);\n clone.key = event.key || '';\n clone.keyCode = event.keyCode || 0;\n clone.which = event.keyCode || 0;\n clone.ctrlKey = event.ctrlKey || false;\n clone.altKey = event.altKey || false;\n clone.shiftKey = event.shiftKey || false;\n clone.metaKey = event.metaKey || false;\n clone.view = event.view || window;\n return clone;\n }\n})(Private || (Private = {}));\n\nexport { CommandRegistry };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nfunction* chain(...objects) {\n for (const object of objects) {\n yield* object;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nfunction* empty() {\n return;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nfunction* enumerate(object, start = 0) {\n for (const value of object) {\n yield [start++, value];\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* filter(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nfunction find(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nfunction findIndex(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nfunction min(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nfunction max(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nfunction minmax(object, fn) {\n let empty = true;\n let vmin;\n let vmax;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n }\n else if (fn(value, vmin) < 0) {\n vmin = value;\n }\n else if (fn(value, vmax) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin, vmax];\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nfunction toArray(object) {\n return Array.from(object);\n}\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nfunction toObject(object) {\n const result = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nfunction each(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nfunction every(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nfunction some(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* map(object, fn) {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nfunction* range(start, stop, step) {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n }\n else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nfunction reduce(object, fn, initial) {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n // Setup the initial accumlated value.\n let accumulator;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n }\n else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n // Iterate the rest of the values, updating the accumulator.\n let next;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n // Return the final accumulated value.\n return accumulator;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nfunction* repeat(value, count) {\n while (0 < count--) {\n yield value;\n }\n}\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nfunction* once(value) {\n yield value;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nfunction* retro(object) {\n if (typeof object.retro === 'function') {\n yield* object.retro();\n }\n else {\n for (let index = object.length - 1; index > -1; index--) {\n yield object[index];\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nfunction* stride(object, step) {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nfunction* take(object, count) {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nfunction* zip(...objects) {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n\nexport { ArrayExt, StringExt, chain, each, empty, enumerate, every, filter, find, findIndex, map, max, min, minmax, once, range, reduce, repeat, retro, some, stride, take, toArray, toObject, topologicSort, zip };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2019, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for clipboard related functionality.\n */\nvar ClipboardExt;\n(function (ClipboardExt) {\n /**\n * Copy text to the system clipboard.\n *\n * @param text - The text to copy to the clipboard.\n */\n function copyText(text) {\n // Fetch the document body.\n const body = document.body;\n // Set up the clipboard event listener.\n const handler = (event) => {\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Set the clipboard data.\n event.clipboardData.setData('text', text);\n // Remove the event listener.\n body.removeEventListener('copy', handler, true);\n };\n // Add the event listener.\n body.addEventListener('copy', handler, true);\n // Trigger the event.\n document.execCommand('copy');\n }\n ClipboardExt.copyText = copyText;\n})(ClipboardExt || (ClipboardExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for element related utilities.\n */\nvar ElementExt;\n(function (ElementExt) {\n /**\n * Compute the box sizing for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The box sizing data for the specified element.\n */\n function boxSizing(element) {\n let style = window.getComputedStyle(element);\n let bt = parseFloat(style.borderTopWidth) || 0;\n let bl = parseFloat(style.borderLeftWidth) || 0;\n let br = parseFloat(style.borderRightWidth) || 0;\n let bb = parseFloat(style.borderBottomWidth) || 0;\n let pt = parseFloat(style.paddingTop) || 0;\n let pl = parseFloat(style.paddingLeft) || 0;\n let pr = parseFloat(style.paddingRight) || 0;\n let pb = parseFloat(style.paddingBottom) || 0;\n let hs = bl + pl + pr + br;\n let vs = bt + pt + pb + bb;\n return {\n borderTop: bt,\n borderLeft: bl,\n borderRight: br,\n borderBottom: bb,\n paddingTop: pt,\n paddingLeft: pl,\n paddingRight: pr,\n paddingBottom: pb,\n horizontalSum: hs,\n verticalSum: vs\n };\n }\n ElementExt.boxSizing = boxSizing;\n /**\n * Compute the size limits for an element.\n *\n * @param element - The element of interest.\n *\n * @returns The size limit data for the specified element.\n */\n function sizeLimits(element) {\n let style = window.getComputedStyle(element);\n let minWidth = parseFloat(style.minWidth) || 0;\n let minHeight = parseFloat(style.minHeight) || 0;\n let maxWidth = parseFloat(style.maxWidth) || Infinity;\n let maxHeight = parseFloat(style.maxHeight) || Infinity;\n maxWidth = Math.max(minWidth, maxWidth);\n maxHeight = Math.max(minHeight, maxHeight);\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n ElementExt.sizeLimits = sizeLimits;\n /**\n * Test whether a client position lies within an element.\n *\n * @param element - The DOM element of interest.\n *\n * @param clientX - The client X coordinate of interest.\n *\n * @param clientY - The client Y coordinate of interest.\n *\n * @returns Whether the point is within the given element.\n */\n function hitTest(element, clientX, clientY) {\n let rect = element.getBoundingClientRect();\n return (clientX >= rect.left &&\n clientX < rect.right &&\n clientY >= rect.top &&\n clientY < rect.bottom);\n }\n ElementExt.hitTest = hitTest;\n /**\n * Vertically scroll an element into view if needed.\n *\n * @param area - The scroll area element.\n *\n * @param element - The element of interest.\n *\n * #### Notes\n * This follows the \"nearest\" behavior of the native `scrollIntoView`\n * method, which is not supported by all browsers.\n * https://drafts.csswg.org/cssom-view/#element-scrolling-members\n *\n * If the element fully covers the visible area or is fully contained\n * within the visible area, no scrolling will take place. Otherwise,\n * the nearest edges of the area and element are aligned.\n */\n function scrollIntoViewIfNeeded(area, element) {\n let ar = area.getBoundingClientRect();\n let er = element.getBoundingClientRect();\n if (er.top <= ar.top && er.bottom >= ar.bottom) {\n return;\n }\n if (er.top < ar.top && er.height <= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.bottom > ar.bottom && er.height >= ar.height) {\n area.scrollTop -= ar.top - er.top;\n return;\n }\n if (er.top < ar.top && er.height > ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n if (er.bottom > ar.bottom && er.height < ar.height) {\n area.scrollTop -= ar.bottom - er.bottom;\n return;\n }\n }\n ElementExt.scrollIntoViewIfNeeded = scrollIntoViewIfNeeded;\n})(ElementExt || (ElementExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for platform related utilities.\n */\nvar Platform;\n(function (Platform) {\n /**\n * A flag indicating whether the platform is Mac.\n */\n Platform.IS_MAC = !!navigator.platform.match(/Mac/i);\n /**\n * A flag indicating whether the platform is Windows.\n */\n Platform.IS_WIN = !!navigator.platform.match(/Win/i);\n /**\n * A flag indicating whether the browser is IE.\n */\n Platform.IS_IE = /Trident/.test(navigator.userAgent);\n /**\n * A flag indicating whether the browser is Edge.\n */\n Platform.IS_EDGE = /Edge/.test(navigator.userAgent);\n /**\n * Test whether the `accel` key is pressed.\n *\n * @param event - The keyboard or mouse event of interest.\n *\n * @returns Whether the `accel` key is pressed.\n *\n * #### Notes\n * On Mac the `accel` key is the command key. On all other\n * platforms the `accel` key is the control key.\n */\n function accelKey(event) {\n return Platform.IS_MAC ? event.metaKey : event.ctrlKey;\n }\n Platform.accelKey = accelKey;\n})(Platform || (Platform = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for selector related utilities.\n */\nvar Selector;\n(function (Selector) {\n /**\n * Calculate the specificity of a single CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns The specificity of the selector.\n *\n * #### Undefined Behavior\n * The selector is invalid.\n *\n * #### Notes\n * This is based on https://www.w3.org/TR/css3-selectors/#specificity\n *\n * A larger number represents a more specific selector.\n *\n * The smallest possible specificity is `0`.\n *\n * The result is represented as a hex number `0x` where\n * each component is the count of the respective selector clause.\n *\n * If the selector contains commas, only the first clause is used.\n *\n * The computed result is cached, so subsequent calculations for the\n * same selector are extremely fast.\n */\n function calculateSpecificity(selector) {\n if (selector in Private.specificityCache) {\n return Private.specificityCache[selector];\n }\n let result = Private.calculateSingle(selector);\n return (Private.specificityCache[selector] = result);\n }\n Selector.calculateSpecificity = calculateSpecificity;\n /**\n * Test whether a selector is a valid CSS selector.\n *\n * @param selector - The CSS selector of interest.\n *\n * @returns `true` if the selector is valid, `false` otherwise.\n *\n * #### Notes\n * The computed result is cached, so subsequent tests for the same\n * selector are extremely fast.\n */\n function isValid(selector) {\n if (selector in Private.validityCache) {\n return Private.validityCache[selector];\n }\n let result = true;\n try {\n Private.testElem.querySelector(selector);\n }\n catch (err) {\n result = false;\n }\n return (Private.validityCache[selector] = result);\n }\n Selector.isValid = isValid;\n /**\n * Test whether an element matches a CSS selector.\n *\n * @param element - The element of interest.\n *\n * @param selector - The valid CSS selector of interest.\n *\n * @returns `true` if the element is a match, `false` otherwise.\n *\n * #### Notes\n * This function uses the builtin browser capabilities when possible,\n * falling back onto a document query otherwise.\n */\n function matches(element, selector) {\n return Private.protoMatchFunc.call(element, selector);\n }\n Selector.matches = matches;\n})(Selector || (Selector = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A cache of computed selector specificity values.\n */\n Private.specificityCache = Object.create(null);\n /**\n * A cache of computed selector validity.\n */\n Private.validityCache = Object.create(null);\n /**\n * An empty element for testing selector validity.\n */\n Private.testElem = document.createElement('div');\n /**\n * A cross-browser CSS selector matching prototype function.\n */\n Private.protoMatchFunc = (() => {\n let proto = Element.prototype;\n return (proto.matches ||\n proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector ||\n function (selector) {\n let elem = this;\n let matches = elem.ownerDocument\n ? elem.ownerDocument.querySelectorAll(selector)\n : [];\n return Array.prototype.indexOf.call(matches, elem) !== -1;\n });\n })();\n /**\n * Calculate the specificity of a single selector.\n *\n * The behavior is undefined if the selector is invalid.\n */\n function calculateSingle(selector) {\n // Ignore anything after the first comma.\n selector = selector.split(',', 1)[0];\n // Setup the aggregate counters.\n let a = 0;\n let b = 0;\n let c = 0;\n // Apply a regex to the front of the selector. If it succeeds, that\n // portion of the selector is removed. Returns a success/fail flag.\n function match(re) {\n let match = selector.match(re);\n if (match === null) {\n return false;\n }\n selector = selector.slice(match[0].length);\n return true;\n }\n // Replace the negation pseudo-class (which is ignored),\n // but keep its inner content (which is not ignored).\n selector = selector.replace(NEGATION_RE, ' $1 ');\n // Continue matching until the selector is consumed.\n while (selector.length > 0) {\n // Match an ID selector.\n if (match(ID_RE)) {\n a++;\n continue;\n }\n // Match a class selector.\n if (match(CLASS_RE)) {\n b++;\n continue;\n }\n // Match an attribute selector.\n if (match(ATTR_RE)) {\n b++;\n continue;\n }\n // Match a pseudo-element selector. This is done before matching\n // a pseudo-class since this regex overlaps with that regex.\n if (match(PSEUDO_ELEM_RE)) {\n c++;\n continue;\n }\n // Match a pseudo-class selector.\n if (match(PSEDUO_CLASS_RE)) {\n b++;\n continue;\n }\n // Match a plain type selector.\n if (match(TYPE_RE)) {\n c++;\n continue;\n }\n // Finally, match any ignored characters.\n if (match(IGNORE_RE)) {\n continue;\n }\n // At this point, the selector is assumed to be invalid.\n return 0;\n }\n // Clamp each component to a reasonable base.\n a = Math.min(a, 0xff);\n b = Math.min(b, 0xff);\n c = Math.min(c, 0xff);\n // Combine the components into a single result.\n return (a << 16) | (b << 8) | c;\n }\n Private.calculateSingle = calculateSingle;\n /**\n * A regex which matches an ID selector at string start.\n */\n const ID_RE = /^#[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a class selector at string start.\n */\n const CLASS_RE = /^\\.[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches an attribute selector at string start.\n */\n const ATTR_RE = /^\\[[^\\]]+\\]/;\n /**\n * A regex which matches a type selector at string start.\n */\n const TYPE_RE = /^[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches a pseudo-element selector at string start.\n */\n const PSEUDO_ELEM_RE = /^(::[^\\s\\+>~#\\.\\[:]+|:first-line|:first-letter|:before|:after)/;\n /**\n * A regex which matches a pseudo-class selector at string start.\n */\n const PSEDUO_CLASS_RE = /^:[^\\s\\+>~#\\.\\[:]+/;\n /**\n * A regex which matches ignored characters at string start.\n */\n const IGNORE_RE = /^[\\s\\+>~\\*]+/;\n /**\n * A regex which matches the negation pseudo-class globally.\n */\n const NEGATION_RE = /:not\\(([^\\)]+)\\)/g;\n})(Private || (Private = {}));\n\nexport { ClipboardExt, ElementExt, Platform, Selector };\n//# sourceMappingURL=index.es6.js.map\n","/**\n * A generic doubly-linked list.\n */\nclass LinkedList {\n constructor() {\n this._first = null;\n this._last = null;\n this._size = 0;\n }\n /**\n * Whether the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get isEmpty() {\n return this._size === 0;\n }\n /**\n * The size of the list.\n *\n * #### Complexity\n * `O(1)`\n *\n * #### Notes\n * This is equivalent to `length`.\n */\n get size() {\n return this._size;\n }\n /**\n * The length of the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `size`.\n *\n * This property is deprecated.\n */\n get length() {\n return this._size;\n }\n /**\n * The first value in the list.\n *\n * This is `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get first() {\n return this._first ? this._first.value : undefined;\n }\n /**\n * The last value in the list.\n *\n * This is `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get last() {\n return this._last ? this._last.value : undefined;\n }\n /**\n * The first node in the list.\n *\n * This is `null` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get firstNode() {\n return this._first;\n }\n /**\n * The last node in the list.\n *\n * This is `null` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n get lastNode() {\n return this._last;\n }\n /**\n * Create an iterator over the values in the list.\n *\n * @returns A new iterator starting with the first value.\n *\n * #### Complexity\n * Constant.\n */\n *[Symbol.iterator]() {\n let node = this._first;\n while (node) {\n yield node.value;\n node = node.next;\n }\n }\n /**\n * Create a reverse iterator over the values in the list.\n *\n * @returns A new iterator starting with the last value.\n *\n * #### Complexity\n * Constant.\n */\n *retro() {\n let node = this._last;\n while (node) {\n yield node.value;\n node = node.prev;\n }\n }\n /**\n * Create an iterator over the nodes in the list.\n *\n * @returns A new iterator starting with the first node.\n *\n * #### Complexity\n * Constant.\n */\n *nodes() {\n let node = this._first;\n while (node) {\n yield node;\n node = node.next;\n }\n }\n /**\n * Create a reverse iterator over the nodes in the list.\n *\n * @returns A new iterator starting with the last node.\n *\n * #### Complexity\n * Constant.\n */\n *retroNodes() {\n let node = this._last;\n while (node) {\n yield node;\n node = node.prev;\n }\n }\n /**\n * Assign new values to the list, replacing all current values.\n *\n * @param values - The values to assign to the list.\n *\n * #### Complexity\n * Linear.\n */\n assign(values) {\n this.clear();\n for (const value of values) {\n this.addLast(value);\n }\n }\n /**\n * Add a value to the end of the list.\n *\n * @param value - The value to add to the end of the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `addLast`.\n */\n push(value) {\n this.addLast(value);\n }\n /**\n * Remove and return the value at the end of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `removeLast`.\n */\n pop() {\n return this.removeLast();\n }\n /**\n * Add a value to the beginning of the list.\n *\n * @param value - The value to add to the beginning of the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `addFirst`.\n */\n shift(value) {\n this.addFirst(value);\n }\n /**\n * Remove and return the value at the beginning of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * This is equivalent to `removeFirst`.\n */\n unshift() {\n return this.removeFirst();\n }\n /**\n * Add a value to the beginning of the list.\n *\n * @param value - The value to add to the beginning of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Complexity\n * Constant.\n */\n addFirst(value) {\n let node = new Private.LinkedListNode(this, value);\n if (!this._first) {\n this._first = node;\n this._last = node;\n }\n else {\n node.next = this._first;\n this._first.prev = node;\n this._first = node;\n }\n this._size++;\n return node;\n }\n /**\n * Add a value to the end of the list.\n *\n * @param value - The value to add to the end of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Complexity\n * Constant.\n */\n addLast(value) {\n let node = new Private.LinkedListNode(this, value);\n if (!this._last) {\n this._first = node;\n this._last = node;\n }\n else {\n node.prev = this._last;\n this._last.next = node;\n this._last = node;\n }\n this._size++;\n return node;\n }\n /**\n * Insert a value before a specific node in the list.\n *\n * @param value - The value to insert before the reference node.\n *\n * @param ref - The reference node of interest. If this is `null`,\n * the value will be added to the beginning of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Notes\n * The reference node must be owned by the list.\n *\n * #### Complexity\n * Constant.\n */\n insertBefore(value, ref) {\n if (!ref || ref === this._first) {\n return this.addFirst(value);\n }\n if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {\n throw new Error('Reference node is not owned by the list.');\n }\n let node = new Private.LinkedListNode(this, value);\n let _ref = ref;\n let prev = _ref.prev;\n node.next = _ref;\n node.prev = prev;\n _ref.prev = node;\n prev.next = node;\n this._size++;\n return node;\n }\n /**\n * Insert a value after a specific node in the list.\n *\n * @param value - The value to insert after the reference node.\n *\n * @param ref - The reference node of interest. If this is `null`,\n * the value will be added to the end of the list.\n *\n * @returns The list node which holds the value.\n *\n * #### Notes\n * The reference node must be owned by the list.\n *\n * #### Complexity\n * Constant.\n */\n insertAfter(value, ref) {\n if (!ref || ref === this._last) {\n return this.addLast(value);\n }\n if (!(ref instanceof Private.LinkedListNode) || ref.list !== this) {\n throw new Error('Reference node is not owned by the list.');\n }\n let node = new Private.LinkedListNode(this, value);\n let _ref = ref;\n let next = _ref.next;\n node.next = next;\n node.prev = _ref;\n _ref.next = node;\n next.prev = node;\n this._size++;\n return node;\n }\n /**\n * Remove and return the value at the beginning of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n removeFirst() {\n let node = this._first;\n if (!node) {\n return undefined;\n }\n if (node === this._last) {\n this._first = null;\n this._last = null;\n }\n else {\n this._first = node.next;\n this._first.prev = null;\n }\n node.list = null;\n node.next = null;\n node.prev = null;\n this._size--;\n return node.value;\n }\n /**\n * Remove and return the value at the end of the list.\n *\n * @returns The removed value, or `undefined` if the list is empty.\n *\n * #### Complexity\n * Constant.\n */\n removeLast() {\n let node = this._last;\n if (!node) {\n return undefined;\n }\n if (node === this._first) {\n this._first = null;\n this._last = null;\n }\n else {\n this._last = node.prev;\n this._last.next = null;\n }\n node.list = null;\n node.next = null;\n node.prev = null;\n this._size--;\n return node.value;\n }\n /**\n * Remove a specific node from the list.\n *\n * @param node - The node to remove from the list.\n *\n * #### Complexity\n * Constant.\n *\n * #### Notes\n * The node must be owned by the list.\n */\n removeNode(node) {\n if (!(node instanceof Private.LinkedListNode) || node.list !== this) {\n throw new Error('Node is not owned by the list.');\n }\n let _node = node;\n if (_node === this._first && _node === this._last) {\n this._first = null;\n this._last = null;\n }\n else if (_node === this._first) {\n this._first = _node.next;\n this._first.prev = null;\n }\n else if (_node === this._last) {\n this._last = _node.prev;\n this._last.next = null;\n }\n else {\n _node.next.prev = _node.prev;\n _node.prev.next = _node.next;\n }\n _node.list = null;\n _node.next = null;\n _node.prev = null;\n this._size--;\n }\n /**\n * Remove all values from the list.\n *\n * #### Complexity\n * Linear.\n */\n clear() {\n let node = this._first;\n while (node) {\n let next = node.next;\n node.list = null;\n node.prev = null;\n node.next = null;\n node = next;\n }\n this._first = null;\n this._last = null;\n this._size = 0;\n }\n}\n/**\n * The namespace for the `LinkedList` class statics.\n */\n(function (LinkedList) {\n /**\n * Create a linked list from an iterable of values.\n *\n * @param values - The iterable object of interest.\n *\n * @returns A new linked list initialized with the given values.\n *\n * #### Complexity\n * Linear.\n */\n function from(values) {\n let list = new LinkedList();\n list.assign(values);\n return list;\n }\n LinkedList.from = from;\n})(LinkedList || (LinkedList = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The internal linked list node implementation.\n */\n class LinkedListNode {\n /**\n * Construct a new linked list node.\n *\n * @param list - The list which owns the node.\n *\n * @param value - The value for the link.\n */\n constructor(list, value) {\n /**\n * The linked list which created and owns the node.\n */\n this.list = null;\n /**\n * The next node in the list.\n */\n this.next = null;\n /**\n * The previous node in the list.\n */\n this.prev = null;\n this.list = list;\n this.value = value;\n }\n }\n Private.LinkedListNode = LinkedListNode;\n})(Private || (Private = {}));\n\nexport { LinkedList };\n//# sourceMappingURL=index.es6.js.map\n","import { every, retro, some, ArrayExt } from '@lumino/algorithm';\nimport { LinkedList } from '@lumino/collections';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module messaging\n */\n/**\n * A message which can be delivered to a message handler.\n *\n * #### Notes\n * This class may be subclassed to create complex message types.\n */\nclass Message {\n /**\n * Construct a new message.\n *\n * @param type - The type of the message.\n */\n constructor(type) {\n this.type = type;\n }\n /**\n * Test whether the message is conflatable.\n *\n * #### Notes\n * Message conflation is an advanced topic. Most message types will\n * not make use of this feature.\n *\n * If a conflatable message is posted to a handler while another\n * conflatable message of the same `type` has already been posted\n * to the handler, the `conflate()` method of the existing message\n * will be invoked. If that method returns `true`, the new message\n * will not be enqueued. This allows messages to be compressed, so\n * that only a single instance of the message type is processed per\n * cycle, no matter how many times messages of that type are posted.\n *\n * Custom message types may reimplement this property.\n *\n * The default implementation is always `false`.\n */\n get isConflatable() {\n return false;\n }\n /**\n * Conflate this message with another message of the same `type`.\n *\n * @param other - A conflatable message of the same `type`.\n *\n * @returns `true` if the message was successfully conflated, or\n * `false` otherwise.\n *\n * #### Notes\n * Message conflation is an advanced topic. Most message types will\n * not make use of this feature.\n *\n * This method is called automatically by the message loop when the\n * given message is posted to the handler paired with this message.\n * This message will already be enqueued and conflatable, and the\n * given message will have the same `type` and also be conflatable.\n *\n * This method should merge the state of the other message into this\n * message as needed so that when this message is finally delivered\n * to the handler, it receives the most up-to-date information.\n *\n * If this method returns `true`, it signals that the other message\n * was successfully conflated and that message will not be enqueued.\n *\n * If this method returns `false`, the other message will be enqueued\n * for normal delivery.\n *\n * Custom message types may reimplement this method.\n *\n * The default implementation always returns `false`.\n */\n conflate(other) {\n return false;\n }\n}\n/**\n * A convenience message class which conflates automatically.\n *\n * #### Notes\n * Message conflation is an advanced topic. Most user code will not\n * make use of this class.\n *\n * This message class is useful for creating message instances which\n * should be conflated, but which have no state other than `type`.\n *\n * If conflation of stateful messages is required, a custom `Message`\n * subclass should be created.\n */\nclass ConflatableMessage extends Message {\n /**\n * Test whether the message is conflatable.\n *\n * #### Notes\n * This property is always `true`.\n */\n get isConflatable() {\n return true;\n }\n /**\n * Conflate this message with another message of the same `type`.\n *\n * #### Notes\n * This method always returns `true`.\n */\n conflate(other) {\n return true;\n }\n}\n/**\n * The namespace for the global singleton message loop.\n */\nvar MessageLoop;\n(function (MessageLoop) {\n /**\n * A function that cancels the pending loop task; `null` if unavailable.\n */\n let pending = null;\n /**\n * Schedules a function for invocation as soon as possible asynchronously.\n *\n * @param fn The function to invoke when called back.\n *\n * @returns An anonymous function that will unschedule invocation if possible.\n */\n const schedule = (resolved => (fn) => {\n let rejected = false;\n resolved.then(() => !rejected && fn());\n return () => {\n rejected = true;\n };\n })(Promise.resolve());\n /**\n * Send a message to a message handler to process immediately.\n *\n * @param handler - The handler which should process the message.\n *\n * @param msg - The message to deliver to the handler.\n *\n * #### Notes\n * The message will first be sent through any installed message hooks\n * for the handler. If the message passes all hooks, it will then be\n * delivered to the `processMessage` method of the handler.\n *\n * The message will not be conflated with pending posted messages.\n *\n * Exceptions in hooks and handlers will be caught and logged.\n */\n function sendMessage(handler, msg) {\n // Lookup the message hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Handle the common case of no installed hooks.\n if (!hooks || hooks.length === 0) {\n invokeHandler(handler, msg);\n return;\n }\n // Invoke the message hooks starting with the newest first.\n let passed = every(retro(hooks), hook => {\n return hook ? invokeHook(hook, handler, msg) : true;\n });\n // Invoke the handler if the message passes all hooks.\n if (passed) {\n invokeHandler(handler, msg);\n }\n }\n MessageLoop.sendMessage = sendMessage;\n /**\n * Post a message to a message handler to process in the future.\n *\n * @param handler - The handler which should process the message.\n *\n * @param msg - The message to post to the handler.\n *\n * #### Notes\n * The message will be conflated with the pending posted messages for\n * the handler, if possible. If the message is not conflated, it will\n * be queued for normal delivery on the next cycle of the event loop.\n *\n * Exceptions in hooks and handlers will be caught and logged.\n */\n function postMessage(handler, msg) {\n // Handle the common case of a non-conflatable message.\n if (!msg.isConflatable) {\n enqueueMessage(handler, msg);\n return;\n }\n // Conflate the message with an existing message if possible.\n let conflated = some(messageQueue, posted => {\n if (posted.handler !== handler) {\n return false;\n }\n if (!posted.msg) {\n return false;\n }\n if (posted.msg.type !== msg.type) {\n return false;\n }\n if (!posted.msg.isConflatable) {\n return false;\n }\n return posted.msg.conflate(msg);\n });\n // Enqueue the message if it was not conflated.\n if (!conflated) {\n enqueueMessage(handler, msg);\n }\n }\n MessageLoop.postMessage = postMessage;\n /**\n * Install a message hook for a message handler.\n *\n * @param handler - The message handler of interest.\n *\n * @param hook - The message hook to install.\n *\n * #### Notes\n * A message hook is invoked before a message is delivered to the\n * handler. If the hook returns `false`, no other hooks will be\n * invoked and the message will not be delivered to the handler.\n *\n * The most recently installed message hook is executed first.\n *\n * If the hook is already installed, this is a no-op.\n */\n function installMessageHook(handler, hook) {\n // Look up the hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Bail early if the hook is already installed.\n if (hooks && hooks.indexOf(hook) !== -1) {\n return;\n }\n // Add the hook to the end, so it will be the first to execute.\n if (!hooks) {\n messageHooks.set(handler, [hook]);\n }\n else {\n hooks.push(hook);\n }\n }\n MessageLoop.installMessageHook = installMessageHook;\n /**\n * Remove an installed message hook for a message handler.\n *\n * @param handler - The message handler of interest.\n *\n * @param hook - The message hook to remove.\n *\n * #### Notes\n * It is safe to call this function while the hook is executing.\n *\n * If the hook is not installed, this is a no-op.\n */\n function removeMessageHook(handler, hook) {\n // Lookup the hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Bail early if the hooks do not exist.\n if (!hooks) {\n return;\n }\n // Lookup the index of the hook and bail if not found.\n let i = hooks.indexOf(hook);\n if (i === -1) {\n return;\n }\n // Clear the hook and schedule a cleanup of the array.\n hooks[i] = null;\n scheduleCleanup(hooks);\n }\n MessageLoop.removeMessageHook = removeMessageHook;\n /**\n * Clear all message data associated with a message handler.\n *\n * @param handler - The message handler of interest.\n *\n * #### Notes\n * This will clear all posted messages and hooks for the handler.\n */\n function clearData(handler) {\n // Lookup the hooks for the handler.\n let hooks = messageHooks.get(handler);\n // Clear all messsage hooks for the handler.\n if (hooks && hooks.length > 0) {\n ArrayExt.fill(hooks, null);\n scheduleCleanup(hooks);\n }\n // Clear all posted messages for the handler.\n for (const posted of messageQueue) {\n if (posted.handler === handler) {\n posted.handler = null;\n posted.msg = null;\n }\n }\n }\n MessageLoop.clearData = clearData;\n /**\n * Process the pending posted messages in the queue immediately.\n *\n * #### Notes\n * This function is useful when posted messages must be processed immediately.\n *\n * This function should normally not be needed, but it may be\n * required to work around certain browser idiosyncrasies.\n *\n * Recursing into this function is a no-op.\n */\n function flush() {\n // Bail if recursion is detected or if there is no pending task.\n if (flushGuard || pending === null) {\n return;\n }\n // Unschedule the pending loop task.\n pending();\n pending = null;\n // Run the message loop within the recursion guard.\n flushGuard = true;\n runMessageLoop();\n flushGuard = false;\n }\n MessageLoop.flush = flush;\n /**\n * Get the message loop exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return exceptionHandler;\n }\n MessageLoop.getExceptionHandler = getExceptionHandler;\n /**\n * Set the message loop exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a message handler or a\n * message hook throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = exceptionHandler;\n exceptionHandler = handler;\n return old;\n }\n MessageLoop.setExceptionHandler = setExceptionHandler;\n /**\n * The queue of posted message pairs.\n */\n const messageQueue = new LinkedList();\n /**\n * A mapping of handler to array of installed message hooks.\n */\n const messageHooks = new WeakMap();\n /**\n * A set of message hook arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * The message loop exception handler.\n */\n let exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * A guard flag to prevent flush recursion.\n */\n let flushGuard = false;\n /**\n * Invoke a message hook with the specified handler and message.\n *\n * Returns the result of the hook, or `true` if the hook throws.\n *\n * Exceptions in the hook will be caught and logged.\n */\n function invokeHook(hook, handler, msg) {\n let result = true;\n try {\n if (typeof hook === 'function') {\n result = hook(handler, msg);\n }\n else {\n result = hook.messageHook(handler, msg);\n }\n }\n catch (err) {\n exceptionHandler(err);\n }\n return result;\n }\n /**\n * Invoke a message handler with the specified message.\n *\n * Exceptions in the handler will be caught and logged.\n */\n function invokeHandler(handler, msg) {\n try {\n handler.processMessage(msg);\n }\n catch (err) {\n exceptionHandler(err);\n }\n }\n /**\n * Add a message to the end of the message queue.\n *\n * This will automatically schedule a run of the message loop.\n */\n function enqueueMessage(handler, msg) {\n // Add the posted message to the queue.\n messageQueue.addLast({ handler, msg });\n // Bail if a loop task is already pending.\n if (pending !== null) {\n return;\n }\n // Schedule a run of the message loop.\n pending = schedule(runMessageLoop);\n }\n /**\n * Run an iteration of the message loop.\n *\n * This will process all pending messages in the queue. If a message\n * is added to the queue while the message loop is running, it will\n * be processed on the next cycle of the loop.\n */\n function runMessageLoop() {\n // Clear the task so the next loop can be scheduled.\n pending = null;\n // If the message queue is empty, there is nothing else to do.\n if (messageQueue.isEmpty) {\n return;\n }\n // Add a sentinel value to the end of the queue. The queue will\n // only be processed up to the sentinel. Messages posted during\n // this cycle will execute on the next cycle.\n let sentinel = { handler: null, msg: null };\n messageQueue.addLast(sentinel);\n // Enter the message loop.\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // Remove the first posted message in the queue.\n let posted = messageQueue.removeFirst();\n // If the value is the sentinel, exit the loop.\n if (posted === sentinel) {\n return;\n }\n // Dispatch the message if it has not been cleared.\n if (posted.handler && posted.msg) {\n sendMessage(posted.handler, posted.msg);\n }\n }\n }\n /**\n * Schedule a cleanup of a message hooks array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any `null` hook will\n * be removed from the array.\n */\n function scheduleCleanup(hooks) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(hooks);\n }\n /**\n * Cleanup the message hook arrays in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupHooks);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty hooks in a message hooks array.\n *\n * This will remove any `null` hook from the array.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupHooks(hooks) {\n ArrayExt.removeAllWhere(hooks, isNull);\n }\n /**\n * Test whether a value is `null`.\n */\n function isNull(value) {\n return value === null;\n }\n})(MessageLoop || (MessageLoop = {}));\n\nexport { ConflatableMessage, Message, MessageLoop };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module properties\n */\n/**\n * A class which attaches a value to an external object.\n *\n * #### Notes\n * Attached properties are used to extend the state of an object with\n * semantic data from an unrelated class. They also encapsulate value\n * creation, coercion, and notification.\n *\n * Because attached property values are stored in a hash table, which\n * in turn is stored in a WeakMap keyed on the owner object, there is\n * non-trivial storage overhead involved in their use. The pattern is\n * therefore best used for the storage of rare data.\n */\nclass AttachedProperty {\n /**\n * Construct a new attached property.\n *\n * @param options - The options for initializing the property.\n */\n constructor(options) {\n this._pid = Private.nextPID();\n this.name = options.name;\n this._create = options.create;\n this._coerce = options.coerce || null;\n this._compare = options.compare || null;\n this._changed = options.changed || null;\n }\n /**\n * Get the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @returns The current value of the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and assigned as the current value of the property.\n */\n get(owner) {\n let value;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n value = map[this._pid];\n }\n else {\n value = map[this._pid] = this._createValue(owner);\n }\n return value;\n }\n /**\n * Set the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @param value - The value for the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n set(owner, value) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, value);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Explicitly coerce the current property value for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n coerce(owner) {\n let oldValue;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n }\n else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, oldValue);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n /**\n * Get or create the default value for the given owner.\n */\n _createValue(owner) {\n let create = this._create;\n return create(owner);\n }\n /**\n * Coerce the value for the given owner.\n */\n _coerceValue(owner, value) {\n let coerce = this._coerce;\n return coerce ? coerce(owner, value) : value;\n }\n /**\n * Compare the old value and new value for equality.\n */\n _compareValue(oldValue, newValue) {\n let compare = this._compare;\n return compare ? compare(oldValue, newValue) : oldValue === newValue;\n }\n /**\n * Run the change notification if the given values are different.\n */\n _maybeNotify(owner, oldValue, newValue) {\n let changed = this._changed;\n if (changed && !this._compareValue(oldValue, newValue)) {\n changed(owner, oldValue, newValue);\n }\n }\n}\n/**\n * The namespace for the `AttachedProperty` class statics.\n */\n(function (AttachedProperty) {\n /**\n * Clear the stored property data for the given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * This will clear all property values for the owner, but it will\n * **not** run the change notification for any of the properties.\n */\n function clearData(owner) {\n Private.ownerData.delete(owner);\n }\n AttachedProperty.clearData = clearData;\n})(AttachedProperty || (AttachedProperty = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A weak mapping of property owner to property map.\n */\n Private.ownerData = new WeakMap();\n /**\n * A function which computes successive unique property ids.\n */\n Private.nextPID = (() => {\n let id = 0;\n return () => {\n let rand = Math.random();\n let stem = `${rand}`.slice(2);\n return `pid-${stem}-${id++}`;\n };\n })();\n /**\n * Lookup the data map for the property owner.\n *\n * This will create the map if one does not already exist.\n */\n function ensureMap(owner) {\n let map = Private.ownerData.get(owner);\n if (map) {\n return map;\n }\n map = Object.create(null);\n Private.ownerData.set(owner, map);\n return map;\n }\n Private.ensureMap = ensureMap;\n})(Private || (Private = {}));\n\nexport { AttachedProperty };\n//# sourceMappingURL=index.es6.js.map\n","import { find, ArrayExt } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nclass Signal {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender) {\n this.sender = sender;\n }\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot, thisArg) {\n return Private.connect(this, slot, thisArg);\n }\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot, thisArg) {\n return Private.disconnect(this, slot, thisArg);\n }\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args) {\n Private.emit(this, args);\n }\n}\n/**\n * The namespace for the `Signal` class statics.\n */\n(function (Signal) {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectBetween(sender, receiver) {\n Private.disconnectBetween(sender, receiver);\n }\n Signal.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n Private.disconnectSender(sender);\n }\n Signal.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectReceiver(receiver) {\n Private.disconnectReceiver(receiver);\n }\n Signal.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectAll(object) {\n Private.disconnectAll(object);\n }\n Signal.disconnectAll = disconnectAll;\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n function clearData(object) {\n Private.disconnectAll(object);\n }\n Signal.clearData = clearData;\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return Private.exceptionHandler;\n }\n Signal.getExceptionHandler = getExceptionHandler;\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n Signal.setExceptionHandler = setExceptionHandler;\n})(Signal || (Signal = {}));\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nclass Stream extends Signal {\n constructor() {\n super(...arguments);\n this._pending = new PromiseDelegate();\n }\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator]() {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n }\n catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args) {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n /**\n * Stop the stream's async iteration.\n */\n stop() {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The signal exception handler function.\n */\n Private.exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n function connect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n // Indicate a successful connection.\n return true;\n }\n Private.connect = connect;\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n function disconnect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver);\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n // Indicate a successful disconnection.\n return true;\n }\n Private.disconnect = disconnect;\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectBetween(sender, receiver) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n Private.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver));\n }\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n Private.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectReceiver(receiver) {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender));\n }\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n Private.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n function disconnectAll(object) {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n Private.disconnectAll = disconnectAll;\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n function emit(signal, args) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n Private.emit = emit;\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap();\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap();\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(connections, signal, slot, thisArg) {\n return find(connections, connection => connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg);\n }\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection, args) {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal.sender, args);\n }\n catch (err) {\n Private.exceptionHandler(err);\n }\n }\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection) {\n return connection.signal === null;\n }\n})(Private || (Private = {}));\n\nexport { Signal, Stream };\n//# sourceMappingURL=index.es6.js.map\n","import { DisposableDelegate } from '@lumino/disposable';\n\n/**\n * An object which manages a drag-drop operation.\n *\n * A drag object dispatches four different events to drop targets:\n *\n * - `'lm-dragenter'` - Dispatched when the mouse enters the target\n * element. This event must be canceled in order to receive any\n * of the other events.\n *\n * - `'lm-dragover'` - Dispatched when the mouse moves over the drop\n * target. It must cancel the event and set the `dropAction` to one\n * of the supported actions in order to receive drop events.\n *\n * - `'lm-dragleave'` - Dispatched when the mouse leaves the target\n * element. This includes moving the mouse into child elements.\n *\n * - `'lm-drop'`- Dispatched when the mouse is released over the target\n * element when the target indicates an appropriate drop action. If\n * the event is canceled, the indicated drop action is returned to\n * the initiator through the resolved promise.\n *\n * A drag operation can be terminated at any time by pressing `Escape`\n * or by disposing the drag object.\n *\n * A drag object has the ability to automatically scroll a scrollable\n * element when the mouse is hovered near one of its edges. To enable\n * this, add the `data-lm-dragscroll` attribute to any element which\n * the drag object should consider for scrolling.\n *\n * #### Notes\n * This class is designed to be used when dragging and dropping custom\n * data *within* a single application. It is *not* a replacement for\n * the native drag-drop API. Instead, it provides an API which allows\n * drag operations to be initiated programmatically and enables the\n * transfer of arbitrary non-string objects; features which are not\n * possible with the native drag-drop API.\n */\nclass Drag {\n /**\n * Construct a new drag object.\n *\n * @param options - The options for initializing the drag.\n */\n constructor(options) {\n /**\n * The scroll loop handler function.\n */\n this._onScrollFrame = () => {\n // Bail early if there is no scroll target.\n if (!this._scrollTarget) {\n return;\n }\n // Unpack the scroll target.\n let { element, edge, distance } = this._scrollTarget;\n // Calculate the scroll delta using nonlinear acceleration.\n let d = Private.SCROLL_EDGE_SIZE - distance;\n let f = Math.pow(d / Private.SCROLL_EDGE_SIZE, 2);\n let s = Math.max(1, Math.round(f * Private.SCROLL_EDGE_SIZE));\n // Scroll the element in the specified direction.\n switch (edge) {\n case 'top':\n element.scrollTop -= s;\n break;\n case 'left':\n element.scrollLeft -= s;\n break;\n case 'right':\n element.scrollLeft += s;\n break;\n case 'bottom':\n element.scrollTop += s;\n break;\n }\n // Request the next cycle of the scroll loop.\n requestAnimationFrame(this._onScrollFrame);\n };\n this._disposed = false;\n this._dropAction = 'none';\n this._override = null;\n this._currentTarget = null;\n this._currentElement = null;\n this._promise = null;\n this._scrollTarget = null;\n this._resolve = null;\n this.document = options.document || document;\n this.mimeData = options.mimeData;\n this.dragImage = options.dragImage || null;\n this.proposedAction = options.proposedAction || 'copy';\n this.supportedActions = options.supportedActions || 'all';\n this.source = options.source || null;\n }\n /**\n * Dispose of the resources held by the drag object.\n *\n * #### Notes\n * This will cancel the drag operation if it is active.\n */\n dispose() {\n // Do nothing if the drag object is already disposed.\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n // If there is a current target, dispatch a drag leave event.\n if (this._currentTarget) {\n let event = new PointerEvent('pointerup', {\n bubbles: true,\n cancelable: true,\n clientX: -1,\n clientY: -1\n });\n Private.dispatchDragLeave(this, this._currentTarget, null, event);\n }\n // Finalize the drag object with `'none'`.\n this._finalize('none');\n }\n /**\n * Test whether the drag object is disposed.\n */\n get isDisposed() {\n return this._disposed;\n }\n /**\n * Start the drag operation at the specified client position.\n *\n * @param clientX - The client X position for the drag start.\n *\n * @param clientY - The client Y position for the drag start.\n *\n * @returns A promise which resolves to the result of the drag.\n *\n * #### Notes\n * If the drag has already been started, the promise created by the\n * first call to `start` is returned.\n *\n * If the drag operation has ended, or if the drag object has been\n * disposed, the returned promise will resolve to `'none'`.\n *\n * The drag object will be automatically disposed when drag operation\n * completes. This means `Drag` objects are for single-use only.\n *\n * This method assumes the left mouse button is already held down.\n */\n start(clientX, clientY) {\n // If the drag object is already disposed, resolve to `none`.\n if (this._disposed) {\n return Promise.resolve('none');\n }\n // If the drag has already been started, return the promise.\n if (this._promise) {\n return this._promise;\n }\n // Install the document listeners for the drag object.\n this._addListeners();\n // Attach the drag image at the specified client position.\n this._attachDragImage(clientX, clientY);\n // Create the promise which will be resolved on completion.\n this._promise = new Promise(resolve => {\n this._resolve = resolve;\n });\n // Trigger a fake move event to kick off the drag operation.\n let event = new PointerEvent('pointermove', {\n bubbles: true,\n cancelable: true,\n clientX,\n clientY\n });\n document.dispatchEvent(event);\n // Return the pending promise for the drag operation.\n return this._promise;\n }\n /**\n * Handle the DOM events for the drag operation.\n *\n * @param event - The DOM event sent to the drag object.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the document. It should not be\n * called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n default:\n // Stop all other events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * Move the drag image element to the specified location.\n *\n * This is a no-op if there is no drag image element.\n */\n moveDragImage(clientX, clientY) {\n if (!this.dragImage) {\n return;\n }\n let style = this.dragImage.style;\n style.transform = `translate(${clientX}px, ${clientY}px)`;\n }\n /**\n * Handle the `'pointermove'` event for the drag object.\n */\n _evtPointerMove(event) {\n // Stop all input events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n // Update the current target node and dispatch enter/leave events.\n this._updateCurrentTarget(event);\n // Update the drag scroll element.\n this._updateDragScroll(event);\n // Move the drag image to the specified client position. This is\n // performed *after* dispatching to prevent unnecessary reflows.\n this.moveDragImage(event.clientX, event.clientY);\n }\n /**\n * Handle the `'pointerup'` event for the drag object.\n */\n _evtPointerUp(event) {\n // Stop all input events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n // Do nothing if the left button is not released.\n if (event.button !== 0) {\n return;\n }\n // Update the current target node and dispatch enter/leave events.\n // This prevents a subtle issue where the DOM mutates under the\n // cursor after the last move event but before the drop event.\n this._updateCurrentTarget(event);\n // If there is no current target, finalize with `'none'`.\n if (!this._currentTarget) {\n this._finalize('none');\n return;\n }\n // If the last drop action was `'none'`, dispatch a leave event\n // to the current target and finalize the drag with `'none'`.\n if (this._dropAction === 'none') {\n Private.dispatchDragLeave(this, this._currentTarget, null, event);\n this._finalize('none');\n return;\n }\n // Dispatch the drop event at the current target and finalize\n // with the resulting drop action.\n let action = Private.dispatchDrop(this, this._currentTarget, event);\n this._finalize(action);\n }\n /**\n * Handle the `'keydown'` event for the drag object.\n */\n _evtKeyDown(event) {\n // Stop all input events during drag-drop.\n event.preventDefault();\n event.stopPropagation();\n // Cancel the drag if `Escape` is pressed.\n if (event.keyCode === 27) {\n this.dispose();\n }\n }\n /**\n * Add the document event listeners for the drag object.\n */\n _addListeners() {\n document.addEventListener('pointerdown', this, true);\n document.addEventListener('pointermove', this, true);\n document.addEventListener('pointerup', this, true);\n document.addEventListener('pointerenter', this, true);\n document.addEventListener('pointerleave', this, true);\n document.addEventListener('pointerover', this, true);\n document.addEventListener('pointerout', this, true);\n document.addEventListener('keydown', this, true);\n document.addEventListener('keyup', this, true);\n document.addEventListener('keypress', this, true);\n document.addEventListener('contextmenu', this, true);\n }\n /**\n * Remove the document event listeners for the drag object.\n */\n _removeListeners() {\n document.removeEventListener('pointerdown', this, true);\n document.removeEventListener('pointermove', this, true);\n document.removeEventListener('pointerup', this, true);\n document.removeEventListener('pointerenter', this, true);\n document.removeEventListener('pointerleave', this, true);\n document.removeEventListener('pointerover', this, true);\n document.removeEventListener('pointerout', this, true);\n document.removeEventListener('keydown', this, true);\n document.removeEventListener('keyup', this, true);\n document.removeEventListener('keypress', this, true);\n document.removeEventListener('contextmenu', this, true);\n }\n /**\n * Update the drag scroll element under the mouse.\n */\n _updateDragScroll(event) {\n // Find the scroll target under the mouse.\n let target = Private.findScrollTarget(event);\n // Bail if there is nothing to scroll.\n if (!this._scrollTarget && !target) {\n return;\n }\n // Start the scroll loop if needed.\n if (!this._scrollTarget) {\n setTimeout(this._onScrollFrame, 500);\n }\n // Update the scroll target.\n this._scrollTarget = target;\n }\n /**\n * Update the current target node using the given mouse event.\n */\n _updateCurrentTarget(event) {\n // Fetch common local state.\n let prevTarget = this._currentTarget;\n let currTarget = this._currentTarget;\n let prevElem = this._currentElement;\n // Find the current indicated element at the given position.\n let currElem = Private.findElementBehindBackdrop(event, this.document);\n // Update the current element reference.\n this._currentElement = currElem;\n // If the indicated element changes from the previous iteration,\n // and is different from the current target, dispatch the exit\n // event to the target.\n if (currElem !== prevElem && currElem !== currTarget) {\n Private.dispatchDragExit(this, currTarget, currElem, event);\n }\n // If the indicated element changes from the previous iteration,\n // and is different from the current target, dispatch the enter\n // event and compute the new target element.\n if (currElem !== prevElem && currElem !== currTarget) {\n currTarget = Private.dispatchDragEnter(this, currElem, currTarget, event);\n }\n // If the current target element has changed, update the current\n // target reference and dispatch the leave event to the old target.\n if (currTarget !== prevTarget) {\n this._currentTarget = currTarget;\n Private.dispatchDragLeave(this, prevTarget, currTarget, event);\n }\n // Dispatch the drag over event and update the drop action.\n let action = Private.dispatchDragOver(this, currTarget, event);\n this._setDropAction(action);\n }\n /**\n * Attach the drag image element at the specified location.\n *\n * This is a no-op if there is no drag image element.\n */\n _attachDragImage(clientX, clientY) {\n if (!this.dragImage) {\n return;\n }\n this.dragImage.classList.add('lm-mod-drag-image');\n let style = this.dragImage.style;\n style.pointerEvents = 'none';\n style.position = 'fixed';\n style.transform = `translate(${clientX}px, ${clientY}px)`;\n const body = this.document instanceof Document\n ? this.document.body\n : this.document.firstElementChild;\n body.appendChild(this.dragImage);\n }\n /**\n * Detach the drag image element from the DOM.\n *\n * This is a no-op if there is no drag image element.\n */\n _detachDragImage() {\n if (!this.dragImage) {\n return;\n }\n let parent = this.dragImage.parentNode;\n if (!parent) {\n return;\n }\n parent.removeChild(this.dragImage);\n }\n /**\n * Set the internal drop action state and update the drag cursor.\n */\n _setDropAction(action) {\n action = Private.validateAction(action, this.supportedActions);\n if (this._override && this._dropAction === action) {\n return;\n }\n switch (action) {\n case 'none':\n this._dropAction = action;\n this._override = Drag.overrideCursor('no-drop', this.document);\n break;\n case 'copy':\n this._dropAction = action;\n this._override = Drag.overrideCursor('copy', this.document);\n break;\n case 'link':\n this._dropAction = action;\n this._override = Drag.overrideCursor('alias', this.document);\n break;\n case 'move':\n this._dropAction = action;\n this._override = Drag.overrideCursor('move', this.document);\n break;\n }\n }\n /**\n * Finalize the drag operation and resolve the drag promise.\n */\n _finalize(action) {\n // Store the resolve function as a temp variable.\n let resolve = this._resolve;\n // Remove the document event listeners.\n this._removeListeners();\n // Detach the drag image.\n this._detachDragImage();\n // Dispose of the cursor override.\n if (this._override) {\n this._override.dispose();\n this._override = null;\n }\n // Clear the mime data.\n this.mimeData.clear();\n // Clear the rest of the internal drag state.\n this._disposed = true;\n this._dropAction = 'none';\n this._currentTarget = null;\n this._currentElement = null;\n this._scrollTarget = null;\n this._promise = null;\n this._resolve = null;\n // Finally, resolve the promise to the given drop action.\n if (resolve) {\n resolve(action);\n }\n }\n}\n/**\n * The namespace for the `Drag` class statics.\n */\n(function (Drag) {\n /**\n * A custom event used for drag-drop operations.\n *\n * #### Notes\n * In order to receive `'lm-dragover'`, `'lm-dragleave'`, or `'lm-drop'`\n * events, a drop target must cancel the `'lm-dragenter'` event by\n * calling the event's `preventDefault()` method.\n */\n class Event extends DragEvent {\n constructor(event, options) {\n super(options.type, {\n bubbles: true,\n cancelable: true,\n altKey: event.altKey,\n button: event.button,\n clientX: event.clientX,\n clientY: event.clientY,\n ctrlKey: event.ctrlKey,\n detail: 0,\n metaKey: event.metaKey,\n relatedTarget: options.related,\n screenX: event.screenX,\n screenY: event.screenY,\n shiftKey: event.shiftKey,\n view: window\n });\n const { drag } = options;\n this.dropAction = 'none';\n this.mimeData = drag.mimeData;\n this.proposedAction = drag.proposedAction;\n this.supportedActions = drag.supportedActions;\n this.source = drag.source;\n }\n }\n Drag.Event = Event;\n /**\n * Override the cursor icon for the entire document.\n *\n * @param cursor - The string representing the cursor style.\n *\n * @returns A disposable which will clear the override when disposed.\n *\n * #### Notes\n * The most recent call to `overrideCursor` takes precedence.\n * Disposing an old override has no effect on the current override.\n *\n * This utility function is used by the `Drag` class to override the\n * mouse cursor during a drag-drop operation, but it can also be used\n * by other classes to fix the cursor icon during normal mouse drags.\n *\n * #### Example\n * ```typescript\n * import { Drag } from '@lumino/dragdrop';\n *\n * // Force the cursor to be 'wait' for the entire document.\n * let override = Drag.overrideCursor('wait');\n *\n * // Clear the override by disposing the return value.\n * override.dispose();\n * ```\n */\n function overrideCursor(cursor, doc = document) {\n return Private.overrideCursor(cursor, doc);\n }\n Drag.overrideCursor = overrideCursor;\n})(Drag || (Drag = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The size of a drag scroll edge, in pixels.\n */\n Private.SCROLL_EDGE_SIZE = 20;\n /**\n * Validate the given action is one of the supported actions.\n *\n * Returns the given action or `'none'` if the action is unsupported.\n */\n function validateAction(action, supported) {\n return actionTable[action] & supportedTable[supported] ? action : 'none';\n }\n Private.validateAction = validateAction;\n /**\n * Find the event target using pointer position if given, or otherwise\n * the central position of the backdrop.\n */\n function findElementBehindBackdrop(event, root = document) {\n if (event) {\n // Check if we already cached element for this event.\n if (lastElementEventSearch && event == lastElementEventSearch.event) {\n return lastElementEventSearch.element;\n }\n Private.cursorBackdrop.style.zIndex = '-1000';\n const element = root.elementFromPoint(event.clientX, event.clientY);\n Private.cursorBackdrop.style.zIndex = '';\n lastElementEventSearch = { event, element };\n return element;\n }\n else {\n const transform = Private.cursorBackdrop.style.transform;\n if (lastElementSearch && transform === lastElementSearch.transform) {\n return lastElementSearch.element;\n }\n const bbox = Private.cursorBackdrop.getBoundingClientRect();\n Private.cursorBackdrop.style.zIndex = '-1000';\n const element = root.elementFromPoint(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);\n Private.cursorBackdrop.style.zIndex = '';\n lastElementSearch = { transform, element };\n return element;\n }\n }\n Private.findElementBehindBackdrop = findElementBehindBackdrop;\n let lastElementEventSearch = null;\n let lastElementSearch = null;\n /**\n * Find the drag scroll target under the mouse, if any.\n */\n function findScrollTarget(event) {\n // Look up the client mouse position.\n let x = event.clientX;\n let y = event.clientY;\n // Get the element under the mouse.\n let element = findElementBehindBackdrop(event);\n // Search for a scrollable target based on the mouse position.\n // The null assert in third clause of for-loop is required due to:\n // https://github.com/Microsoft/TypeScript/issues/14143\n for (; element; element = element.parentElement) {\n // Ignore elements which are not marked as scrollable.\n if (!element.hasAttribute('data-lm-dragscroll')) {\n continue;\n }\n // Set up the coordinate offsets for the element.\n let offsetX = 0;\n let offsetY = 0;\n if (element === document.body) {\n offsetX = window.pageXOffset;\n offsetY = window.pageYOffset;\n }\n // Get the element bounds in viewport coordinates.\n let r = element.getBoundingClientRect();\n let top = r.top + offsetY;\n let left = r.left + offsetX;\n let right = left + r.width;\n let bottom = top + r.height;\n // Skip the element if it's not under the mouse.\n if (x < left || x >= right || y < top || y >= bottom) {\n continue;\n }\n // Compute the distance to each edge.\n let dl = x - left + 1;\n let dt = y - top + 1;\n let dr = right - x;\n let db = bottom - y;\n // Find the smallest of the edge distances.\n let distance = Math.min(dl, dt, dr, db);\n // Skip the element if the mouse is not within a scroll edge.\n if (distance > Private.SCROLL_EDGE_SIZE) {\n continue;\n }\n // Set up the edge result variable.\n let edge;\n // Find the edge for the computed distance.\n switch (distance) {\n case db:\n edge = 'bottom';\n break;\n case dt:\n edge = 'top';\n break;\n case dr:\n edge = 'right';\n break;\n case dl:\n edge = 'left';\n break;\n default:\n throw 'unreachable';\n }\n // Compute how much the element can scroll in width and height.\n let dsw = element.scrollWidth - element.clientWidth;\n let dsh = element.scrollHeight - element.clientHeight;\n // Determine if the element should be scrolled for the edge.\n let shouldScroll;\n switch (edge) {\n case 'top':\n shouldScroll = dsh > 0 && element.scrollTop > 0;\n break;\n case 'left':\n shouldScroll = dsw > 0 && element.scrollLeft > 0;\n break;\n case 'right':\n shouldScroll = dsw > 0 && element.scrollLeft < dsw;\n break;\n case 'bottom':\n shouldScroll = dsh > 0 && element.scrollTop < dsh;\n break;\n default:\n throw 'unreachable';\n }\n // Skip the element if it should not be scrolled.\n if (!shouldScroll) {\n continue;\n }\n // Return the drag scroll target.\n return { element, edge, distance };\n }\n // No drag scroll target was found.\n return null;\n }\n Private.findScrollTarget = findScrollTarget;\n /**\n * Dispatch a drag enter event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param currElem - The currently indicated element, or `null`. This\n * is the \"immediate user selection\" from the whatwg spec.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * @returns The element to use as the current drag target. This is the\n * \"current target element\" from the whatwg spec, and may be `null`.\n *\n * #### Notes\n * This largely implements the drag enter portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragEnter(drag, currElem, currTarget, event) {\n // If the current element is null, return null as the new target.\n if (!currElem) {\n return null;\n }\n // Dispatch a drag enter event to the current element.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragenter'\n });\n let canceled = !currElem.dispatchEvent(dragEvent);\n // If the event was canceled, use the current element as the new target.\n if (canceled) {\n return currElem;\n }\n // If the current element is the document body, keep the original target.\n const body = drag.document instanceof Document\n ? drag.document.body\n : drag.document.firstElementChild;\n if (currElem === body) {\n return currTarget;\n }\n // Dispatch a drag enter event on the document body.\n dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragenter'\n });\n body.dispatchEvent(dragEvent);\n // Ignore the event cancellation, and use the body as the new target.\n return body;\n }\n Private.dispatchDragEnter = dispatchDragEnter;\n /**\n * Dispatch a drag exit event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param prevTarget - The previous target element, or `null`. This\n * is the previous \"current target element\" from the whatwg spec.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * #### Notes\n * This largely implements the drag exit portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragExit(drag, prevTarget, currTarget, event) {\n // If the previous target is null, do nothing.\n if (!prevTarget) {\n return;\n }\n // Dispatch the drag exit event to the previous target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragexit'\n });\n prevTarget.dispatchEvent(dragEvent);\n }\n Private.dispatchDragExit = dispatchDragExit;\n /**\n * Dispatch a drag leave event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param prevTarget - The previous target element, or `null`. This\n * is the previous \"current target element\" from the whatwg spec.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * #### Notes\n * This largely implements the drag leave portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragLeave(drag, prevTarget, currTarget, event) {\n // If the previous target is null, do nothing.\n if (!prevTarget) {\n return;\n }\n // Dispatch the drag leave event to the previous target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: currTarget,\n type: 'lm-dragleave'\n });\n prevTarget.dispatchEvent(dragEvent);\n }\n Private.dispatchDragLeave = dispatchDragLeave;\n /**\n * Dispatch a drag over event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * @returns The `DropAction` result of the drag over event.\n *\n * #### Notes\n * This largely implements the drag over portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDragOver(drag, currTarget, event) {\n // If there is no current target, the drop action is none.\n if (!currTarget) {\n return 'none';\n }\n // Dispatch the drag over event to the current target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: null,\n type: 'lm-dragover'\n });\n let canceled = !currTarget.dispatchEvent(dragEvent);\n // If the event was canceled, return the drop action result.\n if (canceled) {\n return dragEvent.dropAction;\n }\n // Otherwise, the effective drop action is none.\n return 'none';\n }\n Private.dispatchDragOver = dispatchDragOver;\n /**\n * Dispatch a drop event to the indicated element.\n *\n * @param drag - The drag object associated with the action.\n *\n * @param currTarget - The current drag target element, or `null`. This\n * is the \"current target element\" from the whatwg spec.\n *\n * @param event - The mouse event related to the action.\n *\n * @returns The `DropAction` result of the drop event.\n *\n * #### Notes\n * This largely implements the drag over portion of the whatwg spec:\n * https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model\n */\n function dispatchDrop(drag, currTarget, event) {\n // If there is no current target, the drop action is none.\n if (!currTarget) {\n return 'none';\n }\n // Dispatch the drop event to the current target.\n let dragEvent = new Drag.Event(event, {\n drag,\n related: null,\n type: 'lm-drop'\n });\n let canceled = !currTarget.dispatchEvent(dragEvent);\n // If the event was canceled, return the drop action result.\n if (canceled) {\n return dragEvent.dropAction;\n }\n // Otherwise, the effective drop action is none.\n return 'none';\n }\n Private.dispatchDrop = dispatchDrop;\n /**\n * A lookup table from drop action to bit value.\n */\n const actionTable = {\n none: 0x0,\n copy: 0x1,\n link: 0x2,\n move: 0x4\n };\n /**\n * A lookup table from supported action to drop action bit mask.\n */\n const supportedTable = {\n none: actionTable['none'],\n copy: actionTable['copy'],\n link: actionTable['link'],\n move: actionTable['move'],\n 'copy-link': actionTable['copy'] | actionTable['link'],\n 'copy-move': actionTable['copy'] | actionTable['move'],\n 'link-move': actionTable['link'] | actionTable['move'],\n all: actionTable['copy'] | actionTable['link'] | actionTable['move']\n };\n /**\n * Implementation of `Drag.overrideCursor`.\n */\n function overrideCursor(cursor, doc = document) {\n let id = ++overrideCursorID;\n const body = doc instanceof Document\n ? doc.body\n : doc.firstElementChild;\n if (!Private.cursorBackdrop.isConnected) {\n // Hide the backdrop until the pointer moves to avoid issues with\n // native double click detection, used in e.g. datagrid editing.\n Private.cursorBackdrop.style.transform = 'scale(0)';\n body.appendChild(Private.cursorBackdrop);\n resetBackdropScroll();\n document.addEventListener('pointermove', alignBackdrop, {\n capture: true,\n passive: true\n });\n Private.cursorBackdrop.addEventListener('scroll', propagateBackdropScroll, {\n capture: true,\n passive: true\n });\n }\n Private.cursorBackdrop.style.cursor = cursor;\n return new DisposableDelegate(() => {\n if (id === overrideCursorID && Private.cursorBackdrop.isConnected) {\n document.removeEventListener('pointermove', alignBackdrop, true);\n Private.cursorBackdrop.removeEventListener('scroll', propagateBackdropScroll, true);\n body.removeChild(Private.cursorBackdrop);\n }\n });\n }\n Private.overrideCursor = overrideCursor;\n /**\n * Move cursor backdrop to match cursor position.\n */\n function alignBackdrop(event) {\n if (!Private.cursorBackdrop) {\n return;\n }\n Private.cursorBackdrop.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;\n }\n /**\n * Propagate the scroll event from the backdrop element to the scroll target.\n * The scroll target is defined by presence of `data-lm-dragscroll` attribute.\n */\n function propagateBackdropScroll(_event) {\n if (!Private.cursorBackdrop) {\n return;\n }\n // Get the element under behind the centre of the cursor backdrop\n // (essentially behind the cursor, but possibly a few pixels off).\n let element = findElementBehindBackdrop();\n if (!element) {\n return;\n }\n // Find scroll target.\n const scrollTarget = element.closest('[data-lm-dragscroll]');\n if (!scrollTarget) {\n return;\n }\n // Apply the scroll delta to the correct target.\n scrollTarget.scrollTop += Private.cursorBackdrop.scrollTop - backdropScrollOrigin;\n scrollTarget.scrollLeft += Private.cursorBackdrop.scrollLeft - backdropScrollOrigin;\n // Center the scroll position.\n resetBackdropScroll();\n }\n /**\n * Reset the backdrop scroll to allow further scrolling.\n */\n function resetBackdropScroll() {\n Private.cursorBackdrop.scrollTop = backdropScrollOrigin;\n Private.cursorBackdrop.scrollLeft = backdropScrollOrigin;\n }\n /**\n * The center of the backdrop node scroll area.\n */\n const backdropScrollOrigin = 500;\n /**\n * Create cursor backdrop node.\n */\n function createCursorBackdrop() {\n const backdrop = document.createElement('div');\n backdrop.classList.add('lm-cursor-backdrop');\n return backdrop;\n }\n /**\n * The internal id for the active cursor override.\n */\n let overrideCursorID = 0;\n /**\n * A backdrop node overriding pointer cursor.\n *\n * #### Notes\n * We use a backdrop node rather than setting the cursor directly on the body\n * because setting it on body requires more extensive style recalculation for\n * reliable application of the cursor, this is the cursor not being overriden\n * when over child elements with another style like `cursor: other!important`.\n */\n Private.cursorBackdrop = createCursorBackdrop();\n})(Private || (Private = {}));\n\nexport { Drag };\n//# sourceMappingURL=index.es6.js.map\n","import { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\n/**\n * A disposable object which delegates to a callback function.\n */\nclass DisposableDelegate {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn) {\n this._fn = fn;\n }\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed() {\n return !this._fn;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n}\n/**\n * An observable disposable object which delegates to a callback function.\n */\nclass ObservableDisposableDelegate extends DisposableDelegate {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * An object which manages a collection of disposable items.\n */\nclass DisposableSet {\n constructor() {\n this._isDisposed = false;\n this._items = new Set();\n }\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item) {\n return this._items.has(item);\n }\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item) {\n this._items.add(item);\n }\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item) {\n this._items.delete(item);\n }\n /**\n * Remove all items from the set.\n */\n clear() {\n this._items.clear();\n }\n}\n/**\n * The namespace for the `DisposableSet` class statics.\n */\n(function (DisposableSet) {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n DisposableSet.from = from;\n})(DisposableSet || (DisposableSet = {}));\n/**\n * An observable object which manages a collection of disposable items.\n */\nclass ObservableDisposableSet extends DisposableSet {\n constructor() {\n super(...arguments);\n this._disposed = new Signal(this);\n }\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n}\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\n(function (ObservableDisposableSet) {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n function from(items) {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n ObservableDisposableSet.from = from;\n})(ObservableDisposableSet || (ObservableDisposableSet = {}));\n\nexport { DisposableDelegate, DisposableSet, ObservableDisposableDelegate, ObservableDisposableSet };\n//# sourceMappingURL=index.es6.js.map\n","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module keyboard\n */\n/**\n * Get the global application keyboard layout instance.\n *\n * @returns The keyboard layout for use by the application.\n *\n * #### Notes\n * The default keyboard layout is US-English.\n */\nfunction getKeyboardLayout() {\n return Private.keyboardLayout;\n}\n/**\n * Set the global application keyboard layout instance.\n *\n * @param - The keyboard layout for use by the application.\n *\n * #### Notes\n * The keyboard layout should typically be set on application startup\n * to a layout which is appropriate for the user's system.\n */\nfunction setKeyboardLayout(layout) {\n Private.keyboardLayout = layout;\n}\n/**\n * A concrete implementation of {@link IKeyboardLayout} based on keycodes.\n *\n * The `keyCode` property of a `'keydown'` event is a browser and OS\n * specific representation of the physical key (not character) which\n * was pressed on a keyboard. While not the most convenient API, it\n * is currently the only one which works reliably on all browsers.\n *\n * This class accepts a user-defined mapping of keycode to key, which\n * allows for reliable shortcuts tailored to the user's system.\n */\nclass KeycodeLayout {\n /**\n * Construct a new keycode layout.\n *\n * @param name - The human readable name for the layout.\n *\n * @param codes - A mapping of keycode to key value.\n *\n * @param modifierKeys - Array of modifier key names\n */\n constructor(name, codes, modifierKeys = []) {\n this.name = name;\n this._codes = codes;\n this._keys = KeycodeLayout.extractKeys(codes);\n this._modifierKeys = KeycodeLayout.convertToKeySet(modifierKeys);\n }\n /**\n * Get an array of the key values supported by the layout.\n *\n * @returns A new array of the supported key values.\n */\n keys() {\n return Object.keys(this._keys);\n }\n /**\n * Test whether the given key is a valid value for the layout.\n *\n * @param key - The user provided key to test for validity.\n *\n * @returns `true` if the key is valid, `false` otherwise.\n */\n isValidKey(key) {\n return key in this._keys;\n }\n /**\n * Test whether the given key is a modifier key.\n *\n * @param key - The user provided key.\n *\n * @returns `true` if the key is a modifier key, `false` otherwise.\n */\n isModifierKey(key) {\n return key in this._modifierKeys;\n }\n /**\n * Get the key for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns The associated key value, or an empty string if\n * the event does not represent a valid primary key.\n */\n keyForKeydownEvent(event) {\n return this._codes[event.keyCode] || '';\n }\n}\n/**\n * The namespace for the `KeycodeLayout` class statics.\n */\n(function (KeycodeLayout) {\n /**\n * Extract the set of keys from a code map.\n *\n * @param code - The code map of interest.\n *\n * @returns A set of the keys in the code map.\n */\n function extractKeys(codes) {\n let keys = Object.create(null);\n for (let c in codes) {\n keys[codes[c]] = true;\n }\n return keys;\n }\n KeycodeLayout.extractKeys = extractKeys;\n /**\n * Convert array of keys to a key set.\n *\n * @param keys - The array that needs to be converted\n *\n * @returns A set of the keys in the array.\n */\n function convertToKeySet(keys) {\n let keySet = Object(null);\n for (let i = 0, n = keys.length; i < n; ++i) {\n keySet[keys[i]] = true;\n }\n return keySet;\n }\n KeycodeLayout.convertToKeySet = convertToKeySet;\n})(KeycodeLayout || (KeycodeLayout = {}));\n/**\n * A keycode-based keyboard layout for US English keyboards.\n *\n * This layout is valid for the following OS/Browser combinations.\n *\n * - Windows\n * - Chrome\n * - Firefox\n * - IE\n *\n * - OSX\n * - Chrome\n * - Firefox\n * - Safari\n *\n * - Linux\n * - Chrome\n * - Firefox\n *\n * Other combinations may also work, but are untested.\n */\nconst EN_US = new KeycodeLayout('en-us', {\n 8: 'Backspace',\n 9: 'Tab',\n 13: 'Enter',\n 16: 'Shift',\n 17: 'Ctrl',\n 18: 'Alt',\n 19: 'Pause',\n 27: 'Escape',\n 32: 'Space',\n 33: 'PageUp',\n 34: 'PageDown',\n 35: 'End',\n 36: 'Home',\n 37: 'ArrowLeft',\n 38: 'ArrowUp',\n 39: 'ArrowRight',\n 40: 'ArrowDown',\n 45: 'Insert',\n 46: 'Delete',\n 48: '0',\n 49: '1',\n 50: '2',\n 51: '3',\n 52: '4',\n 53: '5',\n 54: '6',\n 55: '7',\n 56: '8',\n 57: '9',\n 59: ';',\n 61: '=',\n 65: 'A',\n 66: 'B',\n 67: 'C',\n 68: 'D',\n 69: 'E',\n 70: 'F',\n 71: 'G',\n 72: 'H',\n 73: 'I',\n 74: 'J',\n 75: 'K',\n 76: 'L',\n 77: 'M',\n 78: 'N',\n 79: 'O',\n 80: 'P',\n 81: 'Q',\n 82: 'R',\n 83: 'S',\n 84: 'T',\n 85: 'U',\n 86: 'V',\n 87: 'W',\n 88: 'X',\n 89: 'Y',\n 90: 'Z',\n 91: 'Meta',\n 93: 'ContextMenu',\n 96: '0',\n 97: '1',\n 98: '2',\n 99: '3',\n 100: '4',\n 101: '5',\n 102: '6',\n 103: '7',\n 104: '8',\n 105: '9',\n 106: '*',\n 107: '+',\n 109: '-',\n 110: '.',\n 111: '/',\n 112: 'F1',\n 113: 'F2',\n 114: 'F3',\n 115: 'F4',\n 116: 'F5',\n 117: 'F6',\n 118: 'F7',\n 119: 'F8',\n 120: 'F9',\n 121: 'F10',\n 122: 'F11',\n 123: 'F12',\n 173: '-',\n 186: ';',\n 187: '=',\n 188: ',',\n 189: '-',\n 190: '.',\n 191: '/',\n 192: '`',\n 219: '[',\n 220: '\\\\',\n 221: ']',\n 222: \"'\",\n 224: 'Meta' // firefox\n}, ['Shift', 'Ctrl', 'Alt', 'Meta'] // modifier keys\n);\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The global keyboard layout instance.\n */\n Private.keyboardLayout = EN_US;\n})(Private || (Private = {}));\n\nexport { EN_US, KeycodeLayout, getKeyboardLayout, setKeyboardLayout };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt } from '@lumino/algorithm';\nimport { JSONExt } from '@lumino/coreutils';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport { Platform, Selector } from '@lumino/domutils';\nimport { getKeyboardLayout } from '@lumino/keyboard';\nimport { Signal } from '@lumino/signaling';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module commands\n */\n/**\n * An object which manages a collection of commands.\n *\n * #### Notes\n * A command registry can be used to populate a variety of action-based\n * widgets, such as command palettes, menus, and toolbars.\n */\nclass CommandRegistry {\n constructor() {\n this._timerID = 0;\n this._replaying = false;\n this._keystrokes = [];\n this._keydownEvents = [];\n this._keyBindings = [];\n this._exactKeyMatch = null;\n this._commands = new Map();\n this._commandChanged = new Signal(this);\n this._commandExecuted = new Signal(this);\n this._keyBindingChanged = new Signal(this);\n }\n /**\n * A signal emitted when a command has changed.\n *\n * #### Notes\n * This signal is useful for visual representations of commands which\n * need to refresh when the state of a relevant command has changed.\n */\n get commandChanged() {\n return this._commandChanged;\n }\n /**\n * A signal emitted when a command has executed.\n *\n * #### Notes\n * Care should be taken when consuming this signal. The command system is used\n * by many components for many user actions. Handlers registered with this\n * signal must return quickly to ensure the overall application remains responsive.\n */\n get commandExecuted() {\n return this._commandExecuted;\n }\n /**\n * A signal emitted when a key binding is changed.\n */\n get keyBindingChanged() {\n return this._keyBindingChanged;\n }\n /**\n * A read-only array of the key bindings in the registry.\n */\n get keyBindings() {\n return this._keyBindings;\n }\n /**\n * List the ids of the registered commands.\n *\n * @returns A new array of the registered command ids.\n */\n listCommands() {\n return Array.from(this._commands.keys());\n }\n /**\n * Test whether a specific command is registered.\n *\n * @param id - The id of the command of interest.\n *\n * @returns `true` if the command is registered, `false` otherwise.\n */\n hasCommand(id) {\n return this._commands.has(id);\n }\n /**\n * Add a command to the registry.\n *\n * @param id - The unique id of the command.\n *\n * @param options - The options for the command.\n *\n * @returns A disposable which will remove the command.\n *\n * @throws An error if the given `id` is already registered.\n */\n addCommand(id, options) {\n // Throw an error if the id is already registered.\n if (this._commands.has(id)) {\n throw new Error(`Command '${id}' already registered.`);\n }\n // Add the command to the registry.\n this._commands.set(id, Private.createCommand(options));\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'added' });\n // Return a disposable which will remove the command.\n return new DisposableDelegate(() => {\n // Remove the command from the registry.\n this._commands.delete(id);\n // Emit the `commandChanged` signal.\n this._commandChanged.emit({ id, type: 'removed' });\n });\n }\n /**\n * Notify listeners that the state of a command has changed.\n *\n * @param id - The id of the command which has changed. If more than\n * one command has changed, this argument should be omitted.\n *\n * @throws An error if the given `id` is not registered.\n *\n * #### Notes\n * This method should be called by the command author whenever the\n * application state changes such that the results of the command\n * metadata functions may have changed.\n *\n * This will cause the `commandChanged` signal to be emitted.\n */\n notifyCommandChanged(id) {\n if (id !== undefined && !this._commands.has(id)) {\n throw new Error(`Command '${id}' is not registered.`);\n }\n this._commandChanged.emit({ id, type: id ? 'changed' : 'many-changed' });\n }\n /**\n * Get the description for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The description for the command.\n */\n describedBy(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return Promise.resolve((_a = cmd === null || cmd === void 0 ? void 0 : cmd.describedBy.call(undefined, args)) !== null && _a !== void 0 ? _a : { args: null });\n }\n /**\n * Get the display label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The display label for the command, or an empty string\n * if the command is not registered.\n */\n label(id, args = JSONExt.emptyObject) {\n var _a;\n let cmd = this._commands.get(id);\n return (_a = cmd === null || cmd === void 0 ? void 0 : cmd.label.call(undefined, args)) !== null && _a !== void 0 ? _a : '';\n }\n /**\n * Get the mnemonic index for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The mnemonic index for the command, or `-1` if the\n * command is not registered.\n */\n mnemonic(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.mnemonic.call(undefined, args) : -1;\n }\n /**\n * Get the icon renderer for a specific command.\n *\n * DEPRECATED: if set to a string value, the .icon field will\n * function as an alias for the .iconClass field, for backwards\n * compatibility. In the future when this is removed, the default\n * return type will become undefined.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon renderer for the command or `undefined`.\n */\n icon(id, args = JSONExt.emptyObject) {\n var _a;\n return (_a = this._commands.get(id)) === null || _a === void 0 ? void 0 : _a.icon.call(undefined, args);\n }\n /**\n * Get the icon class for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon class for the command, or an empty string if\n * the command is not registered.\n */\n iconClass(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconClass.call(undefined, args) : '';\n }\n /**\n * Get the icon label for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The icon label for the command, or an empty string if\n * the command is not registered.\n */\n iconLabel(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.iconLabel.call(undefined, args) : '';\n }\n /**\n * Get the short form caption for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The caption for the command, or an empty string if the\n * command is not registered.\n */\n caption(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.caption.call(undefined, args) : '';\n }\n /**\n * Get the usage help text for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The usage text for the command, or an empty string if\n * the command is not registered.\n */\n usage(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.usage.call(undefined, args) : '';\n }\n /**\n * Get the extra class name for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The class name for the command, or an empty string if\n * the command is not registered.\n */\n className(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.className.call(undefined, args) : '';\n }\n /**\n * Get the dataset for a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns The dataset for the command, or an empty dataset if\n * the command is not registered.\n */\n dataset(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.dataset.call(undefined, args) : {};\n }\n /**\n * Test whether a specific command is enabled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is enabled,\n * or `false` if the command is not registered.\n */\n isEnabled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isEnabled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggled.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggled,\n * or `false` if the command is not registered.\n */\n isToggled(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggled.call(undefined, args) : false;\n }\n /**\n * Test whether a specific command is toggleable.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is toggleable,\n * or `false` if the command is not registered.\n */\n isToggleable(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isToggleable : false;\n }\n /**\n * Test whether a specific command is visible.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A boolean indicating whether the command is visible,\n * or `false` if the command is not registered.\n */\n isVisible(id, args = JSONExt.emptyObject) {\n let cmd = this._commands.get(id);\n return cmd ? cmd.isVisible.call(undefined, args) : false;\n }\n /**\n * Execute a specific command.\n *\n * @param id - The id of the command of interest.\n *\n * @param args - The arguments for the command.\n *\n * @returns A promise which resolves with the result of the command.\n *\n * #### Notes\n * The promise will reject if the command throws an exception,\n * or if the command is not registered.\n */\n execute(id, args = JSONExt.emptyObject) {\n // Reject if the command is not registered.\n let cmd = this._commands.get(id);\n if (!cmd) {\n return Promise.reject(new Error(`Command '${id}' not registered.`));\n }\n // Execute the command and reject if an exception is thrown.\n let value;\n try {\n value = cmd.execute.call(undefined, args);\n }\n catch (err) {\n value = Promise.reject(err);\n }\n // Create the return promise which resolves the result.\n let result = Promise.resolve(value);\n // Emit the command executed signal.\n this._commandExecuted.emit({ id, args, result });\n // Return the result promise to the caller.\n return result;\n }\n /**\n * Add a key binding to the registry.\n *\n * @param options - The options for creating the key binding.\n *\n * @returns A disposable which removes the added key binding.\n *\n * #### Notes\n * If multiple key bindings are registered for the same sequence, the\n * binding with the highest selector specificity is executed first. A\n * tie is broken by using the most recently added key binding.\n *\n * Ambiguous key bindings are resolved with a timeout. As an example,\n * suppose two key bindings are registered: one with the key sequence\n * `['Ctrl D']`, and another with `['Ctrl D', 'Ctrl W']`. If the user\n * presses `Ctrl D`, the first binding cannot be immediately executed\n * since the user may intend to complete the chord with `Ctrl W`. For\n * such cases, a timer is used to allow the chord to be completed. If\n * the chord is not completed before the timeout, the first binding\n * is executed.\n */\n addKeyBinding(options) {\n // Create the binding for the given options.\n let binding = Private.createKeyBinding(options);\n // Add the key binding to the bindings array.\n this._keyBindings.push(binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'added' });\n // Return a disposable which will remove the binding.\n return new DisposableDelegate(() => {\n // Remove the binding from the array.\n ArrayExt.removeFirstOf(this._keyBindings, binding);\n // Emit the `bindingChanged` signal.\n this._keyBindingChanged.emit({ binding, type: 'removed' });\n });\n }\n /**\n * Process a `'keydown'` event and invoke a matching key binding.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * #### Notes\n * This should be called in response to a `'keydown'` event in order\n * to invoke the command for the best matching key binding.\n *\n * The registry **does not** install its own listener for `'keydown'`\n * events. This allows the application full control over the nodes\n * and phase for which the registry processes `'keydown'` events.\n *\n * When the keydown event is processed, if the event target or any of its\n * ancestor nodes has a `data-lm-suppress-shortcuts` attribute, its keydown\n * events will not invoke commands.\n */\n processKeydownEvent(event) {\n // Bail immediately if playing back keystrokes.\n if (this._replaying || CommandRegistry.isModifierKeyPressed(event)) {\n return;\n }\n // Get the normalized keystroke for the event.\n let keystroke = CommandRegistry.keystrokeForKeydownEvent(event);\n // If the keystroke is not valid for the keyboard layout, replay\n // any suppressed events and clear the pending state.\n if (!keystroke) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Add the keystroke to the current key sequence.\n this._keystrokes.push(keystroke);\n // Find the exact and partial matches for the key sequence.\n let { exact, partial } = Private.matchKeyBinding(this._keyBindings, this._keystrokes, event);\n // If there is no exact match and no partial match, replay\n // any suppressed events and clear the pending state.\n if (!exact && !partial) {\n this._replayKeydownEvents();\n this._clearPendingState();\n return;\n }\n // Stop propagation of the event. If there is only a partial match,\n // the event will be replayed if a final exact match never occurs.\n event.preventDefault();\n event.stopPropagation();\n // If there is an exact match but no partial match, the exact match\n // can be dispatched immediately. The pending state is cleared so\n // the next key press starts from the default state.\n if (exact && !partial) {\n this._executeKeyBinding(exact);\n this._clearPendingState();\n return;\n }\n // If there is both an exact match and a partial match, the exact\n // match is stored for future dispatch in case the timer expires\n // before a more specific match is triggered.\n if (exact) {\n this._exactKeyMatch = exact;\n }\n // Store the event for possible playback in the future.\n this._keydownEvents.push(event);\n // (Re)start the timer to dispatch the most recent exact match\n // in case the partial match fails to result in an exact match.\n this._startTimer();\n }\n /**\n * Start or restart the pending timeout.\n */\n _startTimer() {\n this._clearTimer();\n this._timerID = window.setTimeout(() => {\n this._onPendingTimeout();\n }, Private.CHORD_TIMEOUT);\n }\n /**\n * Clear the pending timeout.\n */\n _clearTimer() {\n if (this._timerID !== 0) {\n clearTimeout(this._timerID);\n this._timerID = 0;\n }\n }\n /**\n * Replay the keydown events which were suppressed.\n */\n _replayKeydownEvents() {\n if (this._keydownEvents.length === 0) {\n return;\n }\n this._replaying = true;\n this._keydownEvents.forEach(Private.replayKeyEvent);\n this._replaying = false;\n }\n /**\n * Execute the command for the given key binding.\n *\n * If the command is missing or disabled, a warning will be logged.\n */\n _executeKeyBinding(binding) {\n let { command, args } = binding;\n let newArgs = {\n _luminoEvent: { type: 'keybinding', keys: binding.keys },\n ...args\n };\n if (!this.hasCommand(command) || !this.isEnabled(command, newArgs)) {\n let word = this.hasCommand(command) ? 'enabled' : 'registered';\n let keys = binding.keys.join(', ');\n let msg1 = `Cannot execute key binding '${keys}':`;\n let msg2 = `command '${command}' is not ${word}.`;\n console.warn(`${msg1} ${msg2}`);\n return;\n }\n this.execute(command, newArgs);\n }\n /**\n * Clear the internal pending state.\n */\n _clearPendingState() {\n this._clearTimer();\n this._exactKeyMatch = null;\n this._keystrokes.length = 0;\n this._keydownEvents.length = 0;\n }\n /**\n * Handle the partial match timeout.\n */\n _onPendingTimeout() {\n this._timerID = 0;\n if (this._exactKeyMatch) {\n this._executeKeyBinding(this._exactKeyMatch);\n }\n else {\n this._replayKeydownEvents();\n }\n this._clearPendingState();\n }\n}\n/**\n * The namespace for the `CommandRegistry` class statics.\n */\n(function (CommandRegistry) {\n /**\n * Parse a keystroke into its constituent components.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The parsed components of the keystroke.\n *\n * #### Notes\n * The keystroke should be of the form:\n * `[ [ [ ]]]`\n *\n * The supported modifiers are: `Accel`, `Alt`, `Cmd`, `Ctrl`, and\n * `Shift`. The `Accel` modifier is translated to `Cmd` on Mac and\n * `Ctrl` on all other platforms.\n *\n * The parsing is tolerant and will not throw exceptions. Notably:\n * - Duplicate modifiers are ignored.\n * - Extra primary keys are ignored.\n * - The order of modifiers and primary key is irrelevant.\n * - The keystroke parts should be separated by whitespace.\n * - The keystroke is case sensitive.\n */\n function parseKeystroke(keystroke) {\n let key = '';\n let alt = false;\n let cmd = false;\n let ctrl = false;\n let shift = false;\n for (let token of keystroke.split(/\\s+/)) {\n if (token === 'Accel') {\n if (Platform.IS_MAC) {\n cmd = true;\n }\n else {\n ctrl = true;\n }\n }\n else if (token === 'Alt') {\n alt = true;\n }\n else if (token === 'Cmd') {\n cmd = true;\n }\n else if (token === 'Ctrl') {\n ctrl = true;\n }\n else if (token === 'Shift') {\n shift = true;\n }\n else if (token.length > 0) {\n key = token;\n }\n }\n return { cmd, ctrl, alt, shift, key };\n }\n CommandRegistry.parseKeystroke = parseKeystroke;\n /**\n * Normalize a keystroke into a canonical representation.\n *\n * @param keystroke - The keystroke of interest.\n *\n * @returns The normalized representation of the keystroke.\n *\n * #### Notes\n * This normalizes the keystroke by removing duplicate modifiers and\n * extra primary keys, and assembling the parts in a canonical order.\n *\n * The `Cmd` modifier is ignored on non-Mac platforms.\n */\n function normalizeKeystroke(keystroke) {\n let mods = '';\n let parts = parseKeystroke(keystroke);\n if (parts.ctrl) {\n mods += 'Ctrl ';\n }\n if (parts.alt) {\n mods += 'Alt ';\n }\n if (parts.shift) {\n mods += 'Shift ';\n }\n if (parts.cmd && Platform.IS_MAC) {\n mods += 'Cmd ';\n }\n return mods + parts.key;\n }\n CommandRegistry.normalizeKeystroke = normalizeKeystroke;\n /**\n * Get the platform-specific normalized keys for an options object.\n *\n * @param options - The options for the key binding.\n *\n * @returns Array of combined, normalized keys.\n */\n function normalizeKeys(options) {\n let keys;\n if (Platform.IS_WIN) {\n keys = options.winKeys || options.keys;\n }\n else if (Platform.IS_MAC) {\n keys = options.macKeys || options.keys;\n }\n else {\n keys = options.linuxKeys || options.keys;\n }\n return keys.map(normalizeKeystroke);\n }\n CommandRegistry.normalizeKeys = normalizeKeys;\n /**\n * Format keystrokes for display on the local system.\n *\n * If a list of keystrokes is provided, it will be displayed as\n * a comma-separated string\n *\n * @param keystroke The keystrokes to format\n * @returns The keystrokes representation\n */\n function formatKeystroke(keystroke) {\n return typeof keystroke === 'string'\n ? formatSingleKey(keystroke)\n : keystroke.map(formatSingleKey).join(', ');\n function formatSingleKey(key) {\n let mods = [];\n let separator = Platform.IS_MAC ? ' ' : '+';\n let parts = parseKeystroke(key);\n if (parts.ctrl) {\n mods.push('Ctrl');\n }\n if (parts.alt) {\n mods.push('Alt');\n }\n if (parts.shift) {\n mods.push('Shift');\n }\n if (Platform.IS_MAC && parts.cmd) {\n mods.push('Cmd');\n }\n mods.push(parts.key);\n return mods.map(Private.formatKey).join(separator);\n }\n }\n CommandRegistry.formatKeystroke = formatKeystroke;\n /**\n * Check if `'keydown'` event is caused by pressing a modifier key that should be ignored.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns `true` if modifier key was pressed, `false` otherwise.\n */\n function isModifierKeyPressed(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n return layout.isModifierKey(key);\n }\n CommandRegistry.isModifierKeyPressed = isModifierKeyPressed;\n /**\n * Create a normalized keystroke for a `'keydown'` event.\n *\n * @param event - The event object for a `'keydown'` event.\n *\n * @returns A normalized keystroke, or an empty string if the event\n * does not represent a valid keystroke for the given layout.\n */\n function keystrokeForKeydownEvent(event) {\n let layout = getKeyboardLayout();\n let key = layout.keyForKeydownEvent(event);\n if (!key || layout.isModifierKey(key)) {\n return '';\n }\n let mods = [];\n if (event.ctrlKey) {\n mods.push('Ctrl');\n }\n if (event.altKey) {\n mods.push('Alt');\n }\n if (event.shiftKey) {\n mods.push('Shift');\n }\n if (event.metaKey && Platform.IS_MAC) {\n mods.push('Cmd');\n }\n mods.push(key);\n return mods.join(' ');\n }\n CommandRegistry.keystrokeForKeydownEvent = keystrokeForKeydownEvent;\n})(CommandRegistry || (CommandRegistry = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The timeout in ms for triggering a key binding chord.\n */\n Private.CHORD_TIMEOUT = 1000;\n /**\n * Create a normalized command from an options object.\n */\n function createCommand(options) {\n return {\n execute: options.execute,\n describedBy: asFunc(typeof options.describedBy === 'function'\n ? options.describedBy\n : { args: null, ...options.describedBy }, () => {\n return { args: null };\n }),\n label: asFunc(options.label, emptyStringFunc),\n mnemonic: asFunc(options.mnemonic, negativeOneFunc),\n icon: asFunc(options.icon, undefinedFunc),\n iconClass: asFunc(options.iconClass, emptyStringFunc),\n iconLabel: asFunc(options.iconLabel, emptyStringFunc),\n caption: asFunc(options.caption, emptyStringFunc),\n usage: asFunc(options.usage, emptyStringFunc),\n className: asFunc(options.className, emptyStringFunc),\n dataset: asFunc(options.dataset, emptyDatasetFunc),\n isEnabled: options.isEnabled || trueFunc,\n isToggled: options.isToggled || falseFunc,\n isToggleable: options.isToggleable || !!options.isToggled,\n isVisible: options.isVisible || trueFunc\n };\n }\n Private.createCommand = createCommand;\n /**\n * Create a key binding object from key binding options.\n */\n function createKeyBinding(options) {\n return {\n keys: CommandRegistry.normalizeKeys(options),\n selector: validateSelector(options),\n command: options.command,\n args: options.args || JSONExt.emptyObject\n };\n }\n Private.createKeyBinding = createKeyBinding;\n /**\n * Find the key bindings which match a key sequence.\n *\n * This returns a match result which contains the best exact matching\n * binding, and a flag which indicates if there are partial matches.\n */\n function matchKeyBinding(bindings, keys, event) {\n // The current best exact match.\n let exact = null;\n // Whether a partial match has been found.\n let partial = false;\n // The match distance for the exact match.\n let distance = Infinity;\n // The specificity for the exact match.\n let specificity = 0;\n // Iterate over the bindings and search for the best match.\n for (let i = 0, n = bindings.length; i < n; ++i) {\n // Lookup the current binding.\n let binding = bindings[i];\n // Check whether the key binding sequence is a match.\n let sqm = matchSequence(binding.keys, keys);\n // If there is no match, the binding is ignored.\n if (sqm === 0 /* SequenceMatch.None */) {\n continue;\n }\n // If it is a partial match and no other partial match has been\n // found, ensure the selector matches and set the partial flag.\n if (sqm === 2 /* SequenceMatch.Partial */) {\n if (!partial && targetDistance(binding.selector, event) !== -1) {\n partial = true;\n }\n continue;\n }\n // Ignore the match if the selector doesn't match, or if the\n // matched node is farther away than the current best match.\n let td = targetDistance(binding.selector, event);\n if (td === -1 || td > distance) {\n continue;\n }\n // Get the specificity for the selector.\n let sp = Selector.calculateSpecificity(binding.selector);\n // Update the best match if this match is stronger.\n if (!exact || td < distance || sp >= specificity) {\n exact = binding;\n distance = td;\n specificity = sp;\n }\n }\n // Return the match result.\n return { exact, partial };\n }\n Private.matchKeyBinding = matchKeyBinding;\n /**\n * Replay a keyboard event.\n *\n * This synthetically dispatches a clone of the keyboard event.\n */\n function replayKeyEvent(event) {\n event.target.dispatchEvent(cloneKeyboardEvent(event));\n }\n Private.replayKeyEvent = replayKeyEvent;\n function formatKey(key) {\n if (Platform.IS_MAC) {\n return MAC_DISPLAY.hasOwnProperty(key) ? MAC_DISPLAY[key] : key;\n }\n else {\n return WIN_DISPLAY.hasOwnProperty(key) ? WIN_DISPLAY[key] : key;\n }\n }\n Private.formatKey = formatKey;\n const MAC_DISPLAY = {\n Backspace: '⌫',\n Tab: '⇥',\n Enter: '⏎',\n Shift: '⇧',\n Ctrl: '⌃',\n Alt: '⌥',\n Escape: '⎋',\n PageUp: '⇞',\n PageDown: '⇟',\n End: '↘',\n Home: '↖',\n ArrowLeft: '←',\n ArrowUp: '↑',\n ArrowRight: '→',\n ArrowDown: '↓',\n Delete: '⌦',\n Cmd: '⌘'\n };\n const WIN_DISPLAY = {\n Escape: 'Esc',\n PageUp: 'Page Up',\n PageDown: 'Page Down',\n ArrowLeft: 'Left',\n ArrowUp: 'Up',\n ArrowRight: 'Right',\n ArrowDown: 'Down',\n Delete: 'Del'\n };\n /**\n * A singleton empty string function.\n */\n const emptyStringFunc = () => '';\n /**\n * A singleton `-1` number function\n */\n const negativeOneFunc = () => -1;\n /**\n * A singleton true boolean function.\n */\n const trueFunc = () => true;\n /**\n * A singleton false boolean function.\n */\n const falseFunc = () => false;\n /**\n * A singleton empty dataset function.\n */\n const emptyDatasetFunc = () => ({});\n /**\n * A singleton undefined function\n */\n const undefinedFunc = () => undefined;\n /**\n * Cast a value or command func to a command func.\n */\n function asFunc(value, dfault) {\n if (value === undefined) {\n return dfault;\n }\n if (typeof value === 'function') {\n return value;\n }\n return () => value;\n }\n /**\n * Validate the selector for an options object.\n *\n * This returns the validated selector, or throws if the selector is\n * invalid or contains commas.\n */\n function validateSelector(options) {\n if (options.selector.indexOf(',') !== -1) {\n throw new Error(`Selector cannot contain commas: ${options.selector}`);\n }\n if (!Selector.isValid(options.selector)) {\n throw new Error(`Invalid selector: ${options.selector}`);\n }\n return options.selector;\n }\n /**\n * Test whether a key binding sequence matches a key sequence.\n *\n * Returns a `SequenceMatch` value indicating the type of match.\n */\n function matchSequence(bindKeys, userKeys) {\n if (bindKeys.length < userKeys.length) {\n return 0 /* SequenceMatch.None */;\n }\n for (let i = 0, n = userKeys.length; i < n; ++i) {\n if (bindKeys[i] !== userKeys[i]) {\n return 0 /* SequenceMatch.None */;\n }\n }\n if (bindKeys.length > userKeys.length) {\n return 2 /* SequenceMatch.Partial */;\n }\n return 1 /* SequenceMatch.Exact */;\n }\n /**\n * Find the distance from the target node to the first matching node.\n *\n * This traverses the event path from `target` to `currentTarget` and\n * computes the distance from `target` to the first node which matches\n * the CSS selector. If no match is found, `-1` is returned.\n */\n function targetDistance(selector, event) {\n let targ = event.target;\n let curr = event.currentTarget;\n for (let dist = 0; targ !== null; targ = targ.parentElement, ++dist) {\n if (targ.hasAttribute('data-lm-suppress-shortcuts')) {\n return -1;\n }\n if (Selector.matches(targ, selector)) {\n return dist;\n }\n if (targ === curr) {\n return -1;\n }\n }\n return -1;\n }\n /**\n * Clone a keyboard event.\n */\n function cloneKeyboardEvent(event) {\n // A custom event is required because Chrome nulls out the\n // `keyCode` field in user-generated `KeyboardEvent` types.\n let clone = document.createEvent('Event');\n let bubbles = event.bubbles || true;\n let cancelable = event.cancelable || true;\n clone.initEvent(event.type || 'keydown', bubbles, cancelable);\n clone.key = event.key || '';\n clone.keyCode = event.keyCode || 0;\n clone.which = event.keyCode || 0;\n clone.ctrlKey = event.ctrlKey || false;\n clone.altKey = event.altKey || false;\n clone.shiftKey = event.shiftKey || false;\n clone.metaKey = event.metaKey || false;\n clone.view = event.view || window;\n return clone;\n }\n})(Private || (Private = {}));\n\nexport { CommandRegistry };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt } from '@lumino/algorithm';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module virtualdom\n */\n/**\n * A virtual node which represents plain text content.\n *\n * #### Notes\n * User code will not typically create a `VirtualText` node directly.\n * Instead, the `h()` function will be used to create an element tree.\n */\nclass VirtualText {\n /**\n * Construct a new virtual text node.\n *\n * @param content - The text content for the node.\n */\n constructor(content) {\n /**\n * The type of the node.\n *\n * This value can be used as a type guard for discriminating the\n * `VirtualNode` union type.\n */\n this.type = 'text';\n this.content = content;\n }\n}\n/**\n * A virtual node which represents an HTML element.\n *\n * #### Notes\n * User code will not typically create a `VirtualElement` node directly.\n * Instead, the `h()` function will be used to create an element tree.\n */\nclass VirtualElement {\n /**\n * Construct a new virtual element node.\n *\n * @param tag - The element tag name.\n *\n * @param attrs - The element attributes.\n *\n * @param children - The element children.\n *\n * @param renderer - An optional custom renderer for the element.\n */\n constructor(tag, attrs, children, renderer) {\n /**\n * The type of the node.\n *\n * This value can be used as a type guard for discriminating the\n * `VirtualNode` union type.\n */\n this.type = 'element';\n this.tag = tag;\n this.attrs = attrs;\n this.children = children;\n this.renderer = renderer;\n }\n}\n/**\n * DEPRECATED - use VirtualElement with a defined renderer param instead.\n * This class is provided as a backwards compatibility shim\n *\n * A \"pass thru\" virtual node whose children are managed by a render and an\n * unrender callback. The intent of this flavor of virtual node is to make\n * it easy to blend other kinds of virtualdom (eg React) into Phosphor's\n * virtualdom.\n *\n * #### Notes\n * User code will not typically create a `VirtualElementPass` node directly.\n * Instead, the `hpass()` function will be used to create an element tree.\n */\nclass VirtualElementPass extends VirtualElement {\n /**\n * DEPRECATED - use VirtualElement with a defined renderer param instead\n *\n * Construct a new virtual element pass thru node.\n *\n * @param tag - the tag of the parent element of this node. Once the parent\n * element is rendered, it will be passed as an argument to\n * renderer.render\n *\n * @param attrs - attributes that will assigned to the\n * parent element\n *\n * @param renderer - an object with render and unrender\n * functions, each of which should take a single argument of type\n * HTMLElement and return nothing. If null, the parent element\n * will be rendered barren without any children.\n */\n constructor(tag, attrs, renderer) {\n super(tag, attrs, [], renderer || undefined);\n }\n}\nfunction h(tag) {\n let attrs = {};\n let renderer;\n let children = [];\n for (let i = 1, n = arguments.length; i < n; ++i) {\n // eslint-disable-next-line prefer-rest-params\n let arg = arguments[i];\n if (typeof arg === 'string') {\n children.push(new VirtualText(arg));\n }\n else if (arg instanceof VirtualText) {\n children.push(arg);\n }\n else if (arg instanceof VirtualElement) {\n children.push(arg);\n }\n else if (arg instanceof Array) {\n extend(children, arg);\n }\n else if ((i === 1 || i === 2) && arg && typeof arg === 'object') {\n if ('render' in arg) {\n renderer = arg;\n }\n else {\n attrs = arg;\n }\n }\n }\n return new VirtualElement(tag, attrs, children, renderer);\n function extend(array, values) {\n for (let child of values) {\n if (typeof child === 'string') {\n array.push(new VirtualText(child));\n }\n else if (child instanceof VirtualText) {\n array.push(child);\n }\n else if (child instanceof VirtualElement) {\n array.push(child);\n }\n }\n }\n}\n/**\n * The namespace for the `h` function statics.\n */\n(function (h) {\n h.a = h.bind(undefined, 'a');\n h.abbr = h.bind(undefined, 'abbr');\n h.address = h.bind(undefined, 'address');\n h.area = h.bind(undefined, 'area');\n h.article = h.bind(undefined, 'article');\n h.aside = h.bind(undefined, 'aside');\n h.audio = h.bind(undefined, 'audio');\n h.b = h.bind(undefined, 'b');\n h.bdi = h.bind(undefined, 'bdi');\n h.bdo = h.bind(undefined, 'bdo');\n h.blockquote = h.bind(undefined, 'blockquote');\n h.br = h.bind(undefined, 'br');\n h.button = h.bind(undefined, 'button');\n h.canvas = h.bind(undefined, 'canvas');\n h.caption = h.bind(undefined, 'caption');\n h.cite = h.bind(undefined, 'cite');\n h.code = h.bind(undefined, 'code');\n h.col = h.bind(undefined, 'col');\n h.colgroup = h.bind(undefined, 'colgroup');\n h.data = h.bind(undefined, 'data');\n h.datalist = h.bind(undefined, 'datalist');\n h.dd = h.bind(undefined, 'dd');\n h.del = h.bind(undefined, 'del');\n h.dfn = h.bind(undefined, 'dfn');\n h.div = h.bind(undefined, 'div');\n h.dl = h.bind(undefined, 'dl');\n h.dt = h.bind(undefined, 'dt');\n h.em = h.bind(undefined, 'em');\n h.embed = h.bind(undefined, 'embed');\n h.fieldset = h.bind(undefined, 'fieldset');\n h.figcaption = h.bind(undefined, 'figcaption');\n h.figure = h.bind(undefined, 'figure');\n h.footer = h.bind(undefined, 'footer');\n h.form = h.bind(undefined, 'form');\n h.h1 = h.bind(undefined, 'h1');\n h.h2 = h.bind(undefined, 'h2');\n h.h3 = h.bind(undefined, 'h3');\n h.h4 = h.bind(undefined, 'h4');\n h.h5 = h.bind(undefined, 'h5');\n h.h6 = h.bind(undefined, 'h6');\n h.header = h.bind(undefined, 'header');\n h.hr = h.bind(undefined, 'hr');\n h.i = h.bind(undefined, 'i');\n h.iframe = h.bind(undefined, 'iframe');\n h.img = h.bind(undefined, 'img');\n h.input = h.bind(undefined, 'input');\n h.ins = h.bind(undefined, 'ins');\n h.kbd = h.bind(undefined, 'kbd');\n h.label = h.bind(undefined, 'label');\n h.legend = h.bind(undefined, 'legend');\n h.li = h.bind(undefined, 'li');\n h.main = h.bind(undefined, 'main');\n h.map = h.bind(undefined, 'map');\n h.mark = h.bind(undefined, 'mark');\n h.meter = h.bind(undefined, 'meter');\n h.nav = h.bind(undefined, 'nav');\n h.noscript = h.bind(undefined, 'noscript');\n h.object = h.bind(undefined, 'object');\n h.ol = h.bind(undefined, 'ol');\n h.optgroup = h.bind(undefined, 'optgroup');\n h.option = h.bind(undefined, 'option');\n h.output = h.bind(undefined, 'output');\n h.p = h.bind(undefined, 'p');\n h.param = h.bind(undefined, 'param');\n h.pre = h.bind(undefined, 'pre');\n h.progress = h.bind(undefined, 'progress');\n h.q = h.bind(undefined, 'q');\n h.rp = h.bind(undefined, 'rp');\n h.rt = h.bind(undefined, 'rt');\n h.ruby = h.bind(undefined, 'ruby');\n h.s = h.bind(undefined, 's');\n h.samp = h.bind(undefined, 'samp');\n h.section = h.bind(undefined, 'section');\n h.select = h.bind(undefined, 'select');\n h.small = h.bind(undefined, 'small');\n h.source = h.bind(undefined, 'source');\n h.span = h.bind(undefined, 'span');\n h.strong = h.bind(undefined, 'strong');\n h.sub = h.bind(undefined, 'sub');\n h.summary = h.bind(undefined, 'summary');\n h.sup = h.bind(undefined, 'sup');\n h.table = h.bind(undefined, 'table');\n h.tbody = h.bind(undefined, 'tbody');\n h.td = h.bind(undefined, 'td');\n h.textarea = h.bind(undefined, 'textarea');\n h.tfoot = h.bind(undefined, 'tfoot');\n h.th = h.bind(undefined, 'th');\n h.thead = h.bind(undefined, 'thead');\n h.time = h.bind(undefined, 'time');\n h.title = h.bind(undefined, 'title');\n h.tr = h.bind(undefined, 'tr');\n h.track = h.bind(undefined, 'track');\n h.u = h.bind(undefined, 'u');\n h.ul = h.bind(undefined, 'ul');\n h.var_ = h.bind(undefined, 'var');\n h.video = h.bind(undefined, 'video');\n h.wbr = h.bind(undefined, 'wbr');\n})(h || (h = {}));\nfunction hpass(tag) {\n let attrs = {};\n let renderer = null;\n if (arguments.length === 2) {\n // eslint-disable-next-line prefer-rest-params\n const arg = arguments[1];\n if ('render' in arg) {\n renderer = arg;\n }\n else {\n attrs = arg;\n }\n }\n else if (arguments.length === 3) {\n // eslint-disable-next-line prefer-rest-params\n attrs = arguments[1];\n // eslint-disable-next-line prefer-rest-params\n renderer = arguments[2];\n }\n else if (arguments.length > 3) {\n throw new Error('hpass() should be called with 1, 2, or 3 arguments');\n }\n return new VirtualElementPass(tag, attrs, renderer);\n}\n/**\n * The namespace for the virtual DOM rendering functions.\n */\nvar VirtualDOM;\n(function (VirtualDOM) {\n function realize(node) {\n return Private.createDOMNode(node);\n }\n VirtualDOM.realize = realize;\n /**\n * Render virtual DOM content into a host element.\n *\n * @param content - The virtual DOM content to render.\n *\n * @param host - The host element for the rendered content.\n *\n * #### Notes\n * This renders the delta from the previous rendering. It assumes that\n * the content of the host element is not manipulated by external code.\n *\n * Providing `null` content will clear the rendering.\n *\n * Externally modifying the provided content or the host element will\n * result in undefined rendering behavior.\n */\n function render(content, host) {\n let oldContent = Private.hostMap.get(host) || [];\n let newContent = Private.asContentArray(content);\n Private.hostMap.set(host, newContent);\n Private.updateContent(host, oldContent, newContent);\n }\n VirtualDOM.render = render;\n})(VirtualDOM || (VirtualDOM = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * A weak mapping of host element to virtual DOM content.\n */\n Private.hostMap = new WeakMap();\n /**\n * Cast a content value to a content array.\n */\n function asContentArray(value) {\n if (!value) {\n return [];\n }\n if (value instanceof Array) {\n return value;\n }\n return [value];\n }\n Private.asContentArray = asContentArray;\n function createDOMNode(node) {\n // eslint-disable-next-line prefer-rest-params\n let host = arguments[1] || null;\n // eslint-disable-next-line prefer-rest-params\n const before = arguments[2] || null;\n if (host) {\n host.insertBefore(createDOMNode(node), before);\n }\n else {\n // Create a text node for a virtual text node.\n if (node.type === 'text') {\n return document.createTextNode(node.content);\n }\n // Create the HTML element with the specified tag.\n host = document.createElement(node.tag);\n // Add the attributes for the new element.\n addAttrs(host, node.attrs);\n if (node.renderer) {\n node.renderer.render(host, {\n attrs: node.attrs,\n children: node.children\n });\n return host;\n }\n // Recursively populate the element with child content.\n for (let i = 0, n = node.children.length; i < n; ++i) {\n createDOMNode(node.children[i], host);\n }\n }\n return host;\n }\n Private.createDOMNode = createDOMNode;\n /**\n * Update a host element with the delta of the virtual content.\n *\n * This is the core \"diff\" algorithm. There is no explicit \"patch\"\n * phase. The host is patched at each step as the diff progresses.\n */\n function updateContent(host, oldContent, newContent) {\n // Bail early if the content is identical.\n if (oldContent === newContent) {\n return;\n }\n // Collect the old keyed elems into a mapping.\n let oldKeyed = collectKeys(host, oldContent);\n // Create a copy of the old content which can be modified in-place.\n let oldCopy = oldContent.slice();\n // Update the host with the new content. The diff always proceeds\n // forward and never modifies a previously visited index. The old\n // copy array is modified in-place to reflect the changes made to\n // the host children. This causes the stale nodes to be pushed to\n // the end of the host node and removed at the end of the loop.\n let currElem = host.firstChild;\n let newCount = newContent.length;\n for (let i = 0; i < newCount; ++i) {\n // If the old content is exhausted, create a new node.\n if (i >= oldCopy.length) {\n createDOMNode(newContent[i], host);\n continue;\n }\n // Lookup the old and new virtual nodes.\n let oldVNode = oldCopy[i];\n let newVNode = newContent[i];\n // If both elements are identical, there is nothing to do.\n if (oldVNode === newVNode) {\n currElem = currElem.nextSibling;\n continue;\n }\n // Handle the simplest case of in-place text update first.\n if (oldVNode.type === 'text' && newVNode.type === 'text') {\n // Avoid spurious updates for performance.\n if (currElem.textContent !== newVNode.content) {\n currElem.textContent = newVNode.content;\n }\n currElem = currElem.nextSibling;\n continue;\n }\n // If the old or new node is a text node, the other node is now\n // known to be an element node, so create and insert a new node.\n if (oldVNode.type === 'text' || newVNode.type === 'text') {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // If the old XOR new node has a custom renderer,\n // create and insert a new node.\n if (!oldVNode.renderer != !newVNode.renderer) {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // At this point, both nodes are known to be element nodes.\n // If the new elem is keyed, move an old keyed elem to the proper\n // location before proceeding with the diff. The search can start\n // at the current index, since the unmatched old keyed elems are\n // pushed forward in the old copy array.\n let newKey = newVNode.attrs.key;\n if (newKey && newKey in oldKeyed) {\n let pair = oldKeyed[newKey];\n if (pair.vNode !== oldVNode) {\n ArrayExt.move(oldCopy, oldCopy.indexOf(pair.vNode, i + 1), i);\n host.insertBefore(pair.element, currElem);\n oldVNode = pair.vNode;\n currElem = pair.element;\n }\n }\n // If both elements are identical, there is nothing to do.\n if (oldVNode === newVNode) {\n currElem = currElem.nextSibling;\n continue;\n }\n // If the old elem is keyed and does not match the new elem key,\n // create a new node. This is necessary since the old keyed elem\n // may be matched at a later point in the diff.\n let oldKey = oldVNode.attrs.key;\n if (oldKey && oldKey !== newKey) {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // If the tags are different, create a new node.\n if (oldVNode.tag !== newVNode.tag) {\n ArrayExt.insert(oldCopy, i, newVNode);\n createDOMNode(newVNode, host, currElem);\n continue;\n }\n // At this point, the element can be updated in-place.\n // Update the element attributes.\n updateAttrs(currElem, oldVNode.attrs, newVNode.attrs);\n // Update the element content.\n if (newVNode.renderer) {\n newVNode.renderer.render(currElem, {\n attrs: newVNode.attrs,\n children: newVNode.children\n });\n }\n else {\n updateContent(currElem, oldVNode.children, newVNode.children);\n }\n // Step to the next sibling element.\n currElem = currElem.nextSibling;\n }\n // Cleanup stale DOM\n removeContent(host, oldCopy, newCount, true);\n }\n Private.updateContent = updateContent;\n /**\n * Handle cleanup of stale vdom and its associated DOM. The host node is\n * traversed recursively (in depth-first order), and any explicit cleanup\n * required by a child node is carried out when it is visited (eg if a node\n * has a custom renderer, the renderer.unrender function will be called).\n * Once the subtree beneath each child of host has been completely visited,\n * that child will be removed via a call to host.removeChild.\n */\n function removeContent(host, oldContent, newCount, _sentinel) {\n // Dispose of the old nodes pushed to the end of the host.\n for (let i = oldContent.length - 1; i >= newCount; --i) {\n const oldNode = oldContent[i];\n const child = (_sentinel ? host.lastChild : host.childNodes[i]);\n // recursively clean up host children\n if (oldNode.type === 'text') ;\n else if (oldNode.renderer && oldNode.renderer.unrender) {\n oldNode.renderer.unrender(child, {\n attrs: oldNode.attrs,\n children: oldNode.children\n });\n }\n else {\n removeContent(child, oldNode.children, 0, false);\n }\n if (_sentinel) {\n host.removeChild(child);\n }\n }\n }\n /**\n * A set of special-cased attribute names.\n */\n const specialAttrs = {\n key: true,\n className: true,\n htmlFor: true,\n dataset: true,\n style: true\n };\n /**\n * Add element attributes to a newly created HTML element.\n */\n function addAttrs(element, attrs) {\n // Add the inline event listeners and node attributes.\n for (let name in attrs) {\n if (name in specialAttrs) {\n continue;\n }\n if (name.substr(0, 2) === 'on') {\n element[name] = attrs[name];\n }\n else {\n element.setAttribute(name, attrs[name]);\n }\n }\n // Add the element `class` attribute.\n if (attrs.className !== undefined) {\n element.setAttribute('class', attrs.className);\n }\n // Add the element `for` attribute.\n if (attrs.htmlFor !== undefined) {\n element.setAttribute('for', attrs.htmlFor);\n }\n // Add the dataset values.\n if (attrs.dataset) {\n addDataset(element, attrs.dataset);\n }\n // Add the inline styles.\n if (attrs.style) {\n addStyle(element, attrs.style);\n }\n }\n /**\n * Update the element attributes of an HTML element.\n */\n function updateAttrs(element, oldAttrs, newAttrs) {\n // Do nothing if the attrs are the same object.\n if (oldAttrs === newAttrs) {\n return;\n }\n // Setup the strongly typed loop variable.\n let name;\n // Remove attributes and listeners which no longer exist.\n for (name in oldAttrs) {\n if (name in specialAttrs || name in newAttrs) {\n continue;\n }\n if (name.substr(0, 2) === 'on') {\n element[name] = null;\n }\n else {\n element.removeAttribute(name);\n }\n }\n // Add and update new and existing attributes and listeners.\n for (name in newAttrs) {\n if (name in specialAttrs || oldAttrs[name] === newAttrs[name]) {\n continue;\n }\n if (name.substr(0, 2) === 'on') {\n element[name] = newAttrs[name];\n }\n else {\n element.setAttribute(name, newAttrs[name]);\n }\n }\n // Update the element `class` attribute.\n if (oldAttrs.className !== newAttrs.className) {\n if (newAttrs.className !== undefined) {\n element.setAttribute('class', newAttrs.className);\n }\n else {\n element.removeAttribute('class');\n }\n }\n // Add the element `for` attribute.\n if (oldAttrs.htmlFor !== newAttrs.htmlFor) {\n if (newAttrs.htmlFor !== undefined) {\n element.setAttribute('for', newAttrs.htmlFor);\n }\n else {\n element.removeAttribute('for');\n }\n }\n // Update the dataset values.\n if (oldAttrs.dataset !== newAttrs.dataset) {\n updateDataset(element, oldAttrs.dataset || {}, newAttrs.dataset || {});\n }\n // Update the inline styles.\n if (oldAttrs.style !== newAttrs.style) {\n updateStyle(element, oldAttrs.style || {}, newAttrs.style || {});\n }\n }\n /**\n * Add dataset values to a newly created HTML element.\n */\n function addDataset(element, dataset) {\n for (let name in dataset) {\n element.setAttribute(`data-${name}`, dataset[name]);\n }\n }\n /**\n * Update the dataset values of an HTML element.\n */\n function updateDataset(element, oldDataset, newDataset) {\n for (let name in oldDataset) {\n if (!(name in newDataset)) {\n element.removeAttribute(`data-${name}`);\n }\n }\n for (let name in newDataset) {\n if (oldDataset[name] !== newDataset[name]) {\n element.setAttribute(`data-${name}`, newDataset[name]);\n }\n }\n }\n /**\n * Add inline style values to a newly created HTML element.\n */\n function addStyle(element, style) {\n let elemStyle = element.style;\n let name;\n for (name in style) {\n elemStyle[name] = style[name];\n }\n }\n /**\n * Update the inline style values of an HTML element.\n */\n function updateStyle(element, oldStyle, newStyle) {\n let elemStyle = element.style;\n let name;\n for (name in oldStyle) {\n if (!(name in newStyle)) {\n elemStyle[name] = '';\n }\n }\n for (name in newStyle) {\n if (oldStyle[name] !== newStyle[name]) {\n elemStyle[name] = newStyle[name];\n }\n }\n }\n /**\n * Collect a mapping of keyed elements for the host content.\n */\n function collectKeys(host, content) {\n let node = host.firstChild;\n let keyMap = Object.create(null);\n for (let vNode of content) {\n if (vNode.type === 'element' && vNode.attrs.key) {\n keyMap[vNode.attrs.key] = { vNode, element: node };\n }\n node = node.nextSibling;\n }\n return keyMap;\n }\n})(Private || (Private = {}));\n\nexport { VirtualDOM, VirtualElement, VirtualElementPass, VirtualText, h, hpass };\n//# sourceMappingURL=index.es6.js.map\n","import { ArrayExt, StringExt, empty, find, max } from '@lumino/algorithm';\nimport { UUID, JSONExt, MimeData } from '@lumino/coreutils';\nimport { ElementExt, Selector, Platform } from '@lumino/domutils';\nimport { Message, ConflatableMessage, MessageLoop } from '@lumino/messaging';\nimport { AttachedProperty } from '@lumino/properties';\nimport { Signal } from '@lumino/signaling';\nimport { Drag } from '@lumino/dragdrop';\nimport { CommandRegistry } from '@lumino/commands';\nimport { VirtualDOM, h } from '@lumino/virtualdom';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport { getKeyboardLayout } from '@lumino/keyboard';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A sizer object for use with the box engine layout functions.\n *\n * #### Notes\n * A box sizer holds the geometry information for an object along an\n * arbitrary layout orientation.\n *\n * For best performance, this class should be treated as a raw data\n * struct. It should not typically be subclassed.\n */\nclass BoxSizer {\n constructor() {\n /**\n * The preferred size for the sizer.\n *\n * #### Notes\n * The sizer will be given this initial size subject to its size\n * bounds. The sizer will not deviate from this size unless such\n * deviation is required to fit into the available layout space.\n *\n * There is no limit to this value, but it will be clamped to the\n * bounds defined by {@link minSize} and {@link maxSize}.\n *\n * The default value is `0`.\n */\n this.sizeHint = 0;\n /**\n * The minimum size of the sizer.\n *\n * #### Notes\n * The sizer will never be sized less than this value, even if\n * it means the sizer will overflow the available layout space.\n *\n * It is assumed that this value lies in the range `[0, Infinity)`\n * and that it is `<=` to {@link maxSize}. Failure to adhere to this\n * constraint will yield undefined results.\n *\n * The default value is `0`.\n */\n this.minSize = 0;\n /**\n * The maximum size of the sizer.\n *\n * #### Notes\n * The sizer will never be sized greater than this value, even if\n * it means the sizer will underflow the available layout space.\n *\n * It is assumed that this value lies in the range `[0, Infinity]`\n * and that it is `>=` to {@link minSize}. Failure to adhere to this\n * constraint will yield undefined results.\n *\n * The default value is `Infinity`.\n */\n this.maxSize = Infinity;\n /**\n * The stretch factor for the sizer.\n *\n * #### Notes\n * This controls how much the sizer stretches relative to its sibling\n * sizers when layout space is distributed. A stretch factor of zero\n * is special and will cause the sizer to only be resized after all\n * other sizers with a stretch factor greater than zero have been\n * resized to their limits.\n *\n * It is assumed that this value is an integer that lies in the range\n * `[0, Infinity)`. Failure to adhere to this constraint will yield\n * undefined results.\n *\n * The default value is `1`.\n */\n this.stretch = 1;\n /**\n * The computed size of the sizer.\n *\n * #### Notes\n * This value is the output of a call to {@link BoxEngine.calc}. It represents\n * the computed size for the object along the layout orientation,\n * and will always lie in the range `[minSize, maxSize]`.\n *\n * This value is output only.\n *\n * Changing this value will have no effect.\n */\n this.size = 0;\n /**\n * An internal storage property for the layout algorithm.\n *\n * #### Notes\n * This value is used as temporary storage by the layout algorithm.\n *\n * Changing this value will have no effect.\n */\n this.done = false;\n }\n}\n/**\n * The namespace for the box engine layout functions.\n */\nvar BoxEngine;\n(function (BoxEngine) {\n /**\n * Calculate the optimal layout sizes for a sequence of box sizers.\n *\n * This distributes the available layout space among the box sizers\n * according to the following algorithm:\n *\n * 1. Initialize the sizers's size to its size hint and compute the\n * sums for each of size hint, min size, and max size.\n *\n * 2. If the total size hint equals the available space, return.\n *\n * 3. If the available space is less than the total min size, set all\n * sizers to their min size and return.\n *\n * 4. If the available space is greater than the total max size, set\n * all sizers to their max size and return.\n *\n * 5. If the layout space is less than the total size hint, distribute\n * the negative delta as follows:\n *\n * a. Shrink each sizer with a stretch factor greater than zero by\n * an amount proportional to the negative space and the sum of\n * stretch factors. If the sizer reaches its min size, remove\n * it and its stretch factor from the computation.\n *\n * b. If after adjusting all stretch sizers there remains negative\n * space, distribute the space equally among the sizers with a\n * stretch factor of zero. If a sizer reaches its min size,\n * remove it from the computation.\n *\n * 6. If the layout space is greater than the total size hint,\n * distribute the positive delta as follows:\n *\n * a. Expand each sizer with a stretch factor greater than zero by\n * an amount proportional to the postive space and the sum of\n * stretch factors. If the sizer reaches its max size, remove\n * it and its stretch factor from the computation.\n *\n * b. If after adjusting all stretch sizers there remains positive\n * space, distribute the space equally among the sizers with a\n * stretch factor of zero. If a sizer reaches its max size,\n * remove it from the computation.\n *\n * 7. return\n *\n * @param sizers - The sizers for a particular layout line.\n *\n * @param space - The available layout space for the sizers.\n *\n * @returns The delta between the provided available space and the\n * actual consumed space. This value will be zero if the sizers\n * can be adjusted to fit, negative if the available space is too\n * small, and positive if the available space is too large.\n *\n * #### Notes\n * The {@link BoxSizer.size} of each sizer is updated with the computed size.\n *\n * This function can be called at any time to recompute the layout for\n * an existing sequence of sizers. The previously computed results will\n * have no effect on the new output. It is therefore not necessary to\n * create new sizer objects on each resize event.\n */\n function calc(sizers, space) {\n // Bail early if there is nothing to do.\n let count = sizers.length;\n if (count === 0) {\n return space;\n }\n // Setup the size and stretch counters.\n let totalMin = 0;\n let totalMax = 0;\n let totalSize = 0;\n let totalStretch = 0;\n let stretchCount = 0;\n // Setup the sizers and compute the totals.\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n let min = sizer.minSize;\n let max = sizer.maxSize;\n let hint = sizer.sizeHint;\n sizer.done = false;\n sizer.size = Math.max(min, Math.min(hint, max));\n totalSize += sizer.size;\n totalMin += min;\n totalMax += max;\n if (sizer.stretch > 0) {\n totalStretch += sizer.stretch;\n stretchCount++;\n }\n }\n // If the space is equal to the total size, return early.\n if (space === totalSize) {\n return 0;\n }\n // If the space is less than the total min, minimize each sizer.\n if (space <= totalMin) {\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n sizer.size = sizer.minSize;\n }\n return space - totalMin;\n }\n // If the space is greater than the total max, maximize each sizer.\n if (space >= totalMax) {\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n sizer.size = sizer.maxSize;\n }\n return space - totalMax;\n }\n // The loops below perform sub-pixel precision sizing. A near zero\n // value is used for compares instead of zero to ensure that the\n // loop terminates when the subdivided space is reasonably small.\n let nearZero = 0.01;\n // A counter which is decremented each time a sizer is resized to\n // its limit. This ensures the loops terminate even if there is\n // space remaining to distribute.\n let notDoneCount = count;\n // Distribute negative delta space.\n if (space < totalSize) {\n // Shrink each stretchable sizer by an amount proportional to its\n // stretch factor. If a sizer reaches its min size it's marked as\n // done. The loop progresses in phases where each sizer is given\n // a chance to consume its fair share for the pass, regardless of\n // whether a sizer before it reached its limit. This continues\n // until the stretchable sizers or the free space is exhausted.\n let freeSpace = totalSize - space;\n while (stretchCount > 0 && freeSpace > nearZero) {\n let distSpace = freeSpace;\n let distStretch = totalStretch;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done || sizer.stretch === 0) {\n continue;\n }\n let amt = (sizer.stretch * distSpace) / distStretch;\n if (sizer.size - amt <= sizer.minSize) {\n freeSpace -= sizer.size - sizer.minSize;\n totalStretch -= sizer.stretch;\n sizer.size = sizer.minSize;\n sizer.done = true;\n notDoneCount--;\n stretchCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size -= amt;\n }\n }\n }\n // Distribute any remaining space evenly among the non-stretchable\n // sizers. This progresses in phases in the same manner as above.\n while (notDoneCount > 0 && freeSpace > nearZero) {\n let amt = freeSpace / notDoneCount;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done) {\n continue;\n }\n if (sizer.size - amt <= sizer.minSize) {\n freeSpace -= sizer.size - sizer.minSize;\n sizer.size = sizer.minSize;\n sizer.done = true;\n notDoneCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size -= amt;\n }\n }\n }\n }\n // Distribute positive delta space.\n else {\n // Expand each stretchable sizer by an amount proportional to its\n // stretch factor. If a sizer reaches its max size it's marked as\n // done. The loop progresses in phases where each sizer is given\n // a chance to consume its fair share for the pass, regardless of\n // whether a sizer before it reached its limit. This continues\n // until the stretchable sizers or the free space is exhausted.\n let freeSpace = space - totalSize;\n while (stretchCount > 0 && freeSpace > nearZero) {\n let distSpace = freeSpace;\n let distStretch = totalStretch;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done || sizer.stretch === 0) {\n continue;\n }\n let amt = (sizer.stretch * distSpace) / distStretch;\n if (sizer.size + amt >= sizer.maxSize) {\n freeSpace -= sizer.maxSize - sizer.size;\n totalStretch -= sizer.stretch;\n sizer.size = sizer.maxSize;\n sizer.done = true;\n notDoneCount--;\n stretchCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size += amt;\n }\n }\n }\n // Distribute any remaining space evenly among the non-stretchable\n // sizers. This progresses in phases in the same manner as above.\n while (notDoneCount > 0 && freeSpace > nearZero) {\n let amt = freeSpace / notDoneCount;\n for (let i = 0; i < count; ++i) {\n let sizer = sizers[i];\n if (sizer.done) {\n continue;\n }\n if (sizer.size + amt >= sizer.maxSize) {\n freeSpace -= sizer.maxSize - sizer.size;\n sizer.size = sizer.maxSize;\n sizer.done = true;\n notDoneCount--;\n }\n else {\n freeSpace -= amt;\n sizer.size += amt;\n }\n }\n }\n }\n // Indicate that the consumed space equals the available space.\n return 0;\n }\n BoxEngine.calc = calc;\n /**\n * Adjust a sizer by a delta and update its neighbors accordingly.\n *\n * @param sizers - The sizers which should be adjusted.\n *\n * @param index - The index of the sizer to grow.\n *\n * @param delta - The amount to adjust the sizer, positive or negative.\n *\n * #### Notes\n * This will adjust the indicated sizer by the specified amount, along\n * with the sizes of the appropriate neighbors, subject to the limits\n * specified by each of the sizers.\n *\n * This is useful when implementing box layouts where the boundaries\n * between the sizers are interactively adjustable by the user.\n */\n function adjust(sizers, index, delta) {\n // Bail early when there is nothing to do.\n if (sizers.length === 0 || delta === 0) {\n return;\n }\n // Dispatch to the proper implementation.\n if (delta > 0) {\n growSizer(sizers, index, delta);\n }\n else {\n shrinkSizer(sizers, index, -delta);\n }\n }\n BoxEngine.adjust = adjust;\n /**\n * Grow a sizer by a positive delta and adjust neighbors.\n */\n function growSizer(sizers, index, delta) {\n // Compute how much the items to the left can expand.\n let growLimit = 0;\n for (let i = 0; i <= index; ++i) {\n let sizer = sizers[i];\n growLimit += sizer.maxSize - sizer.size;\n }\n // Compute how much the items to the right can shrink.\n let shrinkLimit = 0;\n for (let i = index + 1, n = sizers.length; i < n; ++i) {\n let sizer = sizers[i];\n shrinkLimit += sizer.size - sizer.minSize;\n }\n // Clamp the delta adjustment to the limits.\n delta = Math.min(delta, growLimit, shrinkLimit);\n // Grow the sizers to the left by the delta.\n let grow = delta;\n for (let i = index; i >= 0 && grow > 0; --i) {\n let sizer = sizers[i];\n let limit = sizer.maxSize - sizer.size;\n if (limit >= grow) {\n sizer.sizeHint = sizer.size + grow;\n grow = 0;\n }\n else {\n sizer.sizeHint = sizer.size + limit;\n grow -= limit;\n }\n }\n // Shrink the sizers to the right by the delta.\n let shrink = delta;\n for (let i = index + 1, n = sizers.length; i < n && shrink > 0; ++i) {\n let sizer = sizers[i];\n let limit = sizer.size - sizer.minSize;\n if (limit >= shrink) {\n sizer.sizeHint = sizer.size - shrink;\n shrink = 0;\n }\n else {\n sizer.sizeHint = sizer.size - limit;\n shrink -= limit;\n }\n }\n }\n /**\n * Shrink a sizer by a positive delta and adjust neighbors.\n */\n function shrinkSizer(sizers, index, delta) {\n // Compute how much the items to the right can expand.\n let growLimit = 0;\n for (let i = index + 1, n = sizers.length; i < n; ++i) {\n let sizer = sizers[i];\n growLimit += sizer.maxSize - sizer.size;\n }\n // Compute how much the items to the left can shrink.\n let shrinkLimit = 0;\n for (let i = 0; i <= index; ++i) {\n let sizer = sizers[i];\n shrinkLimit += sizer.size - sizer.minSize;\n }\n // Clamp the delta adjustment to the limits.\n delta = Math.min(delta, growLimit, shrinkLimit);\n // Grow the sizers to the right by the delta.\n let grow = delta;\n for (let i = index + 1, n = sizers.length; i < n && grow > 0; ++i) {\n let sizer = sizers[i];\n let limit = sizer.maxSize - sizer.size;\n if (limit >= grow) {\n sizer.sizeHint = sizer.size + grow;\n grow = 0;\n }\n else {\n sizer.sizeHint = sizer.size + limit;\n grow -= limit;\n }\n }\n // Shrink the sizers to the left by the delta.\n let shrink = delta;\n for (let i = index; i >= 0 && shrink > 0; --i) {\n let sizer = sizers[i];\n let limit = sizer.size - sizer.minSize;\n if (limit >= shrink) {\n sizer.sizeHint = sizer.size - shrink;\n shrink = 0;\n }\n else {\n sizer.sizeHint = sizer.size - limit;\n shrink -= limit;\n }\n }\n }\n})(BoxEngine || (BoxEngine = {}));\n\n/**\n * An object which holds data related to an object's title.\n *\n * #### Notes\n * A title object is intended to hold the data necessary to display a\n * header for a particular object. A common example is the `TabPanel`,\n * which uses the widget title to populate the tab for a child widget.\n *\n * It is the responsibility of the owner to call the title disposal.\n */\nclass Title {\n /**\n * Construct a new title.\n *\n * @param options - The options for initializing the title.\n */\n constructor(options) {\n this._label = '';\n this._caption = '';\n this._mnemonic = -1;\n this._icon = undefined;\n this._iconClass = '';\n this._iconLabel = '';\n this._className = '';\n this._closable = false;\n this._changed = new Signal(this);\n this._isDisposed = false;\n this.owner = options.owner;\n if (options.label !== undefined) {\n this._label = options.label;\n }\n if (options.mnemonic !== undefined) {\n this._mnemonic = options.mnemonic;\n }\n if (options.icon !== undefined) {\n this._icon = options.icon;\n }\n if (options.iconClass !== undefined) {\n this._iconClass = options.iconClass;\n }\n if (options.iconLabel !== undefined) {\n this._iconLabel = options.iconLabel;\n }\n if (options.caption !== undefined) {\n this._caption = options.caption;\n }\n if (options.className !== undefined) {\n this._className = options.className;\n }\n if (options.closable !== undefined) {\n this._closable = options.closable;\n }\n this._dataset = options.dataset || {};\n }\n /**\n * A signal emitted when the state of the title changes.\n */\n get changed() {\n return this._changed;\n }\n /**\n * Get the label for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get label() {\n return this._label;\n }\n /**\n * Set the label for the title.\n */\n set label(value) {\n if (this._label === value) {\n return;\n }\n this._label = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the mnemonic index for the title.\n *\n * #### Notes\n * The default value is `-1`.\n */\n get mnemonic() {\n return this._mnemonic;\n }\n /**\n * Set the mnemonic index for the title.\n */\n set mnemonic(value) {\n if (this._mnemonic === value) {\n return;\n }\n this._mnemonic = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the icon renderer for the title.\n *\n * #### Notes\n * The default value is undefined.\n */\n get icon() {\n return this._icon;\n }\n /**\n * Set the icon renderer for the title.\n *\n * #### Notes\n * A renderer is an object that supplies a render and unrender function.\n */\n set icon(value) {\n if (this._icon === value) {\n return;\n }\n this._icon = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the icon class name for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get iconClass() {\n return this._iconClass;\n }\n /**\n * Set the icon class name for the title.\n *\n * #### Notes\n * Multiple class names can be separated with whitespace.\n */\n set iconClass(value) {\n if (this._iconClass === value) {\n return;\n }\n this._iconClass = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the icon label for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get iconLabel() {\n return this._iconLabel;\n }\n /**\n * Set the icon label for the title.\n *\n * #### Notes\n * Multiple class names can be separated with whitespace.\n */\n set iconLabel(value) {\n if (this._iconLabel === value) {\n return;\n }\n this._iconLabel = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the caption for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get caption() {\n return this._caption;\n }\n /**\n * Set the caption for the title.\n */\n set caption(value) {\n if (this._caption === value) {\n return;\n }\n this._caption = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the extra class name for the title.\n *\n * #### Notes\n * The default value is an empty string.\n */\n get className() {\n return this._className;\n }\n /**\n * Set the extra class name for the title.\n *\n * #### Notes\n * Multiple class names can be separated with whitespace.\n */\n set className(value) {\n if (this._className === value) {\n return;\n }\n this._className = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the closable state for the title.\n *\n * #### Notes\n * The default value is `false`.\n */\n get closable() {\n return this._closable;\n }\n /**\n * Set the closable state for the title.\n *\n * #### Notes\n * This controls the presence of a close icon when applicable.\n */\n set closable(value) {\n if (this._closable === value) {\n return;\n }\n this._closable = value;\n this._changed.emit(undefined);\n }\n /**\n * Get the dataset for the title.\n *\n * #### Notes\n * The default value is an empty dataset.\n */\n get dataset() {\n return this._dataset;\n }\n /**\n * Set the dataset for the title.\n *\n * #### Notes\n * This controls the data attributes when applicable.\n */\n set dataset(value) {\n if (this._dataset === value) {\n return;\n }\n this._dataset = value;\n this._changed.emit(undefined);\n }\n /**\n * Test whether the title has been disposed.\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Dispose of the resources held by the title.\n *\n * #### Notes\n * It is the responsibility of the owner to call the title disposal.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n}\n\n/**\n * The base class of the lumino widget hierarchy.\n *\n * #### Notes\n * This class will typically be subclassed in order to create a useful\n * widget. However, it can be used directly to host externally created\n * content.\n */\nclass Widget {\n /**\n * Construct a new widget.\n *\n * @param options - The options for initializing the widget.\n */\n constructor(options = {}) {\n this._flags = 0;\n this._layout = null;\n this._parent = null;\n this._disposed = new Signal(this);\n this._hiddenMode = Widget.HiddenMode.Display;\n this.node = Private$j.createNode(options);\n this.addClass('lm-Widget');\n }\n /**\n * Dispose of the widget and its descendant widgets.\n *\n * #### Notes\n * It is unsafe to use the widget after it has been disposed.\n *\n * All calls made to this method after the first are a no-op.\n */\n dispose() {\n // Do nothing if the widget is already disposed.\n if (this.isDisposed) {\n return;\n }\n // Set the disposed flag and emit the disposed signal.\n this.setFlag(Widget.Flag.IsDisposed);\n this._disposed.emit(undefined);\n // Remove or detach the widget if necessary.\n if (this.parent) {\n this.parent = null;\n }\n else if (this.isAttached) {\n Widget.detach(this);\n }\n // Dispose of the widget layout.\n if (this._layout) {\n this._layout.dispose();\n this._layout = null;\n }\n // Dispose the title\n this.title.dispose();\n // Clear the extra data associated with the widget.\n Signal.clearData(this);\n MessageLoop.clearData(this);\n AttachedProperty.clearData(this);\n }\n /**\n * A signal emitted when the widget is disposed.\n */\n get disposed() {\n return this._disposed;\n }\n /**\n * Test whether the widget has been disposed.\n */\n get isDisposed() {\n return this.testFlag(Widget.Flag.IsDisposed);\n }\n /**\n * Test whether the widget's node is attached to the DOM.\n */\n get isAttached() {\n return this.testFlag(Widget.Flag.IsAttached);\n }\n /**\n * Test whether the widget is explicitly hidden.\n */\n get isHidden() {\n return this.testFlag(Widget.Flag.IsHidden);\n }\n /**\n * Test whether the widget is visible.\n *\n * #### Notes\n * A widget is visible when it is attached to the DOM, is not\n * explicitly hidden, and has no explicitly hidden ancestors.\n */\n get isVisible() {\n return this.testFlag(Widget.Flag.IsVisible);\n }\n /**\n * The title object for the widget.\n *\n * #### Notes\n * The title object is used by some container widgets when displaying\n * the widget alongside some title, such as a tab panel or side bar.\n *\n * Since not all widgets will use the title, it is created on demand.\n *\n * The `owner` property of the title is set to this widget.\n */\n get title() {\n return Private$j.titleProperty.get(this);\n }\n /**\n * Get the id of the widget's DOM node.\n */\n get id() {\n return this.node.id;\n }\n /**\n * Set the id of the widget's DOM node.\n */\n set id(value) {\n this.node.id = value;\n }\n /**\n * The dataset for the widget's DOM node.\n */\n get dataset() {\n return this.node.dataset;\n }\n /**\n * Get the method for hiding the widget.\n */\n get hiddenMode() {\n return this._hiddenMode;\n }\n /**\n * Set the method for hiding the widget.\n */\n set hiddenMode(value) {\n if (this._hiddenMode === value) {\n return;\n }\n if (this.isHidden) {\n // Reset styles set by previous mode.\n this._toggleHidden(false);\n }\n if (value == Widget.HiddenMode.Scale) {\n this.node.style.willChange = 'transform';\n }\n else {\n this.node.style.willChange = 'auto';\n }\n this._hiddenMode = value;\n if (this.isHidden) {\n // Set styles for new mode.\n this._toggleHidden(true);\n }\n }\n /**\n * Get the parent of the widget.\n */\n get parent() {\n return this._parent;\n }\n /**\n * Set the parent of the widget.\n *\n * #### Notes\n * Children are typically added to a widget by using a layout, which\n * means user code will not normally set the parent widget directly.\n *\n * The widget will be automatically removed from its old parent.\n *\n * This is a no-op if there is no effective parent change.\n */\n set parent(value) {\n if (this._parent === value) {\n return;\n }\n if (value && this.contains(value)) {\n throw new Error('Invalid parent widget.');\n }\n if (this._parent && !this._parent.isDisposed) {\n let msg = new Widget.ChildMessage('child-removed', this);\n MessageLoop.sendMessage(this._parent, msg);\n }\n this._parent = value;\n if (this._parent && !this._parent.isDisposed) {\n let msg = new Widget.ChildMessage('child-added', this);\n MessageLoop.sendMessage(this._parent, msg);\n }\n if (!this.isDisposed) {\n MessageLoop.sendMessage(this, Widget.Msg.ParentChanged);\n }\n }\n /**\n * Get the layout for the widget.\n */\n get layout() {\n return this._layout;\n }\n /**\n * Set the layout for the widget.\n *\n * #### Notes\n * The layout is single-use only. It cannot be changed after the\n * first assignment.\n *\n * The layout is disposed automatically when the widget is disposed.\n */\n set layout(value) {\n if (this._layout === value) {\n return;\n }\n if (this.testFlag(Widget.Flag.DisallowLayout)) {\n throw new Error('Cannot set widget layout.');\n }\n if (this._layout) {\n throw new Error('Cannot change widget layout.');\n }\n if (value.parent) {\n throw new Error('Cannot change layout parent.');\n }\n this._layout = value;\n value.parent = this;\n }\n /**\n * Create an iterator over the widget's children.\n *\n * @returns A new iterator over the children of the widget.\n *\n * #### Notes\n * The widget must have a populated layout in order to have children.\n *\n * If a layout is not installed, the returned iterator will be empty.\n */\n *children() {\n if (this._layout) {\n yield* this._layout;\n }\n }\n /**\n * Test whether a widget is a descendant of this widget.\n *\n * @param widget - The descendant widget of interest.\n *\n * @returns `true` if the widget is a descendant, `false` otherwise.\n */\n contains(widget) {\n for (let value = widget; value; value = value._parent) {\n if (value === this) {\n return true;\n }\n }\n return false;\n }\n /**\n * Test whether the widget's DOM node has the given class name.\n *\n * @param name - The class name of interest.\n *\n * @returns `true` if the node has the class, `false` otherwise.\n */\n hasClass(name) {\n return this.node.classList.contains(name);\n }\n /**\n * Add a class name to the widget's DOM node.\n *\n * @param name - The class name to add to the node.\n *\n * #### Notes\n * If the class name is already added to the node, this is a no-op.\n *\n * The class name must not contain whitespace.\n */\n addClass(name) {\n this.node.classList.add(name);\n }\n /**\n * Remove a class name from the widget's DOM node.\n *\n * @param name - The class name to remove from the node.\n *\n * #### Notes\n * If the class name is not yet added to the node, this is a no-op.\n *\n * The class name must not contain whitespace.\n */\n removeClass(name) {\n this.node.classList.remove(name);\n }\n /**\n * Toggle a class name on the widget's DOM node.\n *\n * @param name - The class name to toggle on the node.\n *\n * @param force - Whether to force add the class (`true`) or force\n * remove the class (`false`). If not provided, the presence of\n * the class will be toggled from its current state.\n *\n * @returns `true` if the class is now present, `false` otherwise.\n *\n * #### Notes\n * The class name must not contain whitespace.\n */\n toggleClass(name, force) {\n if (force === true) {\n this.node.classList.add(name);\n return true;\n }\n if (force === false) {\n this.node.classList.remove(name);\n return false;\n }\n return this.node.classList.toggle(name);\n }\n /**\n * Post an `'update-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for posting the message.\n */\n update() {\n MessageLoop.postMessage(this, Widget.Msg.UpdateRequest);\n }\n /**\n * Post a `'fit-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for posting the message.\n */\n fit() {\n MessageLoop.postMessage(this, Widget.Msg.FitRequest);\n }\n /**\n * Post an `'activate-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for posting the message.\n */\n activate() {\n MessageLoop.postMessage(this, Widget.Msg.ActivateRequest);\n }\n /**\n * Send a `'close-request'` message to the widget.\n *\n * #### Notes\n * This is a simple convenience method for sending the message.\n */\n close() {\n MessageLoop.sendMessage(this, Widget.Msg.CloseRequest);\n }\n /**\n * Show the widget and make it visible to its parent widget.\n *\n * #### Notes\n * This causes the {@link isHidden} property to be `false`.\n *\n * If the widget is not explicitly hidden, this is a no-op.\n */\n show() {\n if (!this.testFlag(Widget.Flag.IsHidden)) {\n return;\n }\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.BeforeShow);\n }\n this.clearFlag(Widget.Flag.IsHidden);\n this._toggleHidden(false);\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.AfterShow);\n }\n if (this.parent) {\n let msg = new Widget.ChildMessage('child-shown', this);\n MessageLoop.sendMessage(this.parent, msg);\n }\n }\n /**\n * Hide the widget and make it hidden to its parent widget.\n *\n * #### Notes\n * This causes the {@link isHidden} property to be `true`.\n *\n * If the widget is explicitly hidden, this is a no-op.\n */\n hide() {\n if (this.testFlag(Widget.Flag.IsHidden)) {\n return;\n }\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.BeforeHide);\n }\n this.setFlag(Widget.Flag.IsHidden);\n this._toggleHidden(true);\n if (this.isAttached && (!this.parent || this.parent.isVisible)) {\n MessageLoop.sendMessage(this, Widget.Msg.AfterHide);\n }\n if (this.parent) {\n let msg = new Widget.ChildMessage('child-hidden', this);\n MessageLoop.sendMessage(this.parent, msg);\n }\n }\n /**\n * Show or hide the widget according to a boolean value.\n *\n * @param hidden - `true` to hide the widget, or `false` to show it.\n *\n * #### Notes\n * This is a convenience method for `hide()` and `show()`.\n */\n setHidden(hidden) {\n if (hidden) {\n this.hide();\n }\n else {\n this.show();\n }\n }\n /**\n * Test whether the given widget flag is set.\n *\n * #### Notes\n * This will not typically be called directly by user code.\n */\n testFlag(flag) {\n return (this._flags & flag) !== 0;\n }\n /**\n * Set the given widget flag.\n *\n * #### Notes\n * This will not typically be called directly by user code.\n */\n setFlag(flag) {\n this._flags |= flag;\n }\n /**\n * Clear the given widget flag.\n *\n * #### Notes\n * This will not typically be called directly by user code.\n */\n clearFlag(flag) {\n this._flags &= ~flag;\n }\n /**\n * Process a message sent to the widget.\n *\n * @param msg - The message sent to the widget.\n *\n * #### Notes\n * Subclasses may reimplement this method as needed.\n */\n processMessage(msg) {\n switch (msg.type) {\n case 'resize':\n this.notifyLayout(msg);\n this.onResize(msg);\n break;\n case 'update-request':\n this.notifyLayout(msg);\n this.onUpdateRequest(msg);\n break;\n case 'fit-request':\n this.notifyLayout(msg);\n this.onFitRequest(msg);\n break;\n case 'before-show':\n this.notifyLayout(msg);\n this.onBeforeShow(msg);\n break;\n case 'after-show':\n this.setFlag(Widget.Flag.IsVisible);\n this.notifyLayout(msg);\n this.onAfterShow(msg);\n break;\n case 'before-hide':\n this.notifyLayout(msg);\n this.onBeforeHide(msg);\n break;\n case 'after-hide':\n this.clearFlag(Widget.Flag.IsVisible);\n this.notifyLayout(msg);\n this.onAfterHide(msg);\n break;\n case 'before-attach':\n this.notifyLayout(msg);\n this.onBeforeAttach(msg);\n break;\n case 'after-attach':\n if (!this.isHidden && (!this.parent || this.parent.isVisible)) {\n this.setFlag(Widget.Flag.IsVisible);\n }\n this.setFlag(Widget.Flag.IsAttached);\n this.notifyLayout(msg);\n this.onAfterAttach(msg);\n break;\n case 'before-detach':\n this.notifyLayout(msg);\n this.onBeforeDetach(msg);\n break;\n case 'after-detach':\n this.clearFlag(Widget.Flag.IsVisible);\n this.clearFlag(Widget.Flag.IsAttached);\n this.notifyLayout(msg);\n this.onAfterDetach(msg);\n break;\n case 'activate-request':\n this.notifyLayout(msg);\n this.onActivateRequest(msg);\n break;\n case 'close-request':\n this.notifyLayout(msg);\n this.onCloseRequest(msg);\n break;\n case 'child-added':\n this.notifyLayout(msg);\n this.onChildAdded(msg);\n break;\n case 'child-removed':\n this.notifyLayout(msg);\n this.onChildRemoved(msg);\n break;\n default:\n this.notifyLayout(msg);\n break;\n }\n }\n /**\n * Invoke the message processing routine of the widget's layout.\n *\n * @param msg - The message to dispatch to the layout.\n *\n * #### Notes\n * This is a no-op if the widget does not have a layout.\n *\n * This will not typically be called directly by user code.\n */\n notifyLayout(msg) {\n if (this._layout) {\n this._layout.processParentMessage(msg);\n }\n }\n /**\n * A message handler invoked on a `'close-request'` message.\n *\n * #### Notes\n * The default implementation unparents or detaches the widget.\n */\n onCloseRequest(msg) {\n if (this.parent) {\n this.parent = null;\n }\n else if (this.isAttached) {\n Widget.detach(this);\n }\n }\n /**\n * A message handler invoked on a `'resize'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onResize(msg) { }\n /**\n * A message handler invoked on an `'update-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onUpdateRequest(msg) { }\n /**\n * A message handler invoked on a `'fit-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onFitRequest(msg) { }\n /**\n * A message handler invoked on an `'activate-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onActivateRequest(msg) { }\n /**\n * A message handler invoked on a `'before-show'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeShow(msg) { }\n /**\n * A message handler invoked on an `'after-show'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterShow(msg) { }\n /**\n * A message handler invoked on a `'before-hide'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeHide(msg) { }\n /**\n * A message handler invoked on an `'after-hide'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterHide(msg) { }\n /**\n * A message handler invoked on a `'before-attach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeAttach(msg) { }\n /**\n * A message handler invoked on an `'after-attach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterAttach(msg) { }\n /**\n * A message handler invoked on a `'before-detach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onBeforeDetach(msg) { }\n /**\n * A message handler invoked on an `'after-detach'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onAfterDetach(msg) { }\n /**\n * A message handler invoked on a `'child-added'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildAdded(msg) { }\n /**\n * A message handler invoked on a `'child-removed'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildRemoved(msg) { }\n _toggleHidden(hidden) {\n if (hidden) {\n switch (this._hiddenMode) {\n case Widget.HiddenMode.Display:\n this.addClass('lm-mod-hidden');\n break;\n case Widget.HiddenMode.Scale:\n this.node.style.transform = 'scale(0)';\n this.node.setAttribute('aria-hidden', 'true');\n break;\n case Widget.HiddenMode.ContentVisibility:\n // @ts-expect-error content-visibility unknown by DOM lib types\n this.node.style.contentVisibility = 'hidden';\n this.node.style.zIndex = '-1';\n break;\n }\n }\n else {\n switch (this._hiddenMode) {\n case Widget.HiddenMode.Display:\n this.removeClass('lm-mod-hidden');\n break;\n case Widget.HiddenMode.Scale:\n this.node.style.transform = '';\n this.node.removeAttribute('aria-hidden');\n break;\n case Widget.HiddenMode.ContentVisibility:\n // @ts-expect-error content-visibility unknown by DOM lib types\n this.node.style.contentVisibility = '';\n this.node.style.zIndex = '';\n break;\n }\n }\n }\n}\n/**\n * The namespace for the `Widget` class statics.\n */\n(function (Widget) {\n (function (HiddenMode) {\n /**\n * Set a `lm-mod-hidden` CSS class to hide the widget using `display:none`\n * CSS from the standard Lumino CSS.\n */\n HiddenMode[HiddenMode[\"Display\"] = 0] = \"Display\";\n /**\n * Hide the widget by setting the `transform` to `'scale(0)'`.\n */\n HiddenMode[HiddenMode[\"Scale\"] = 1] = \"Scale\";\n /**\n *Hide the widget by setting the `content-visibility` to `'hidden'`.\n */\n HiddenMode[HiddenMode[\"ContentVisibility\"] = 2] = \"ContentVisibility\";\n })(Widget.HiddenMode || (Widget.HiddenMode = {}));\n (function (Flag) {\n /**\n * The widget has been disposed.\n */\n Flag[Flag[\"IsDisposed\"] = 1] = \"IsDisposed\";\n /**\n * The widget is attached to the DOM.\n */\n Flag[Flag[\"IsAttached\"] = 2] = \"IsAttached\";\n /**\n * The widget is hidden.\n */\n Flag[Flag[\"IsHidden\"] = 4] = \"IsHidden\";\n /**\n * The widget is visible.\n */\n Flag[Flag[\"IsVisible\"] = 8] = \"IsVisible\";\n /**\n * A layout cannot be set on the widget.\n */\n Flag[Flag[\"DisallowLayout\"] = 16] = \"DisallowLayout\";\n })(Widget.Flag || (Widget.Flag = {}));\n (function (Msg) {\n /**\n * A singleton `'before-show'` message.\n *\n * #### Notes\n * This message is sent to a widget before it becomes visible.\n *\n * This message is **not** sent when the widget is being attached.\n */\n Msg.BeforeShow = new Message('before-show');\n /**\n * A singleton `'after-show'` message.\n *\n * #### Notes\n * This message is sent to a widget after it becomes visible.\n *\n * This message is **not** sent when the widget is being attached.\n */\n Msg.AfterShow = new Message('after-show');\n /**\n * A singleton `'before-hide'` message.\n *\n * #### Notes\n * This message is sent to a widget before it becomes not-visible.\n *\n * This message is **not** sent when the widget is being detached.\n */\n Msg.BeforeHide = new Message('before-hide');\n /**\n * A singleton `'after-hide'` message.\n *\n * #### Notes\n * This message is sent to a widget after it becomes not-visible.\n *\n * This message is **not** sent when the widget is being detached.\n */\n Msg.AfterHide = new Message('after-hide');\n /**\n * A singleton `'before-attach'` message.\n *\n * #### Notes\n * This message is sent to a widget before it is attached.\n */\n Msg.BeforeAttach = new Message('before-attach');\n /**\n * A singleton `'after-attach'` message.\n *\n * #### Notes\n * This message is sent to a widget after it is attached.\n */\n Msg.AfterAttach = new Message('after-attach');\n /**\n * A singleton `'before-detach'` message.\n *\n * #### Notes\n * This message is sent to a widget before it is detached.\n */\n Msg.BeforeDetach = new Message('before-detach');\n /**\n * A singleton `'after-detach'` message.\n *\n * #### Notes\n * This message is sent to a widget after it is detached.\n */\n Msg.AfterDetach = new Message('after-detach');\n /**\n * A singleton `'parent-changed'` message.\n *\n * #### Notes\n * This message is sent to a widget when its parent has changed.\n */\n Msg.ParentChanged = new Message('parent-changed');\n /**\n * A singleton conflatable `'update-request'` message.\n *\n * #### Notes\n * This message can be dispatched to supporting widgets in order to\n * update their content based on the current widget state. Not all\n * widgets will respond to messages of this type.\n *\n * For widgets with a layout, this message will inform the layout to\n * update the position and size of its child widgets.\n */\n Msg.UpdateRequest = new ConflatableMessage('update-request');\n /**\n * A singleton conflatable `'fit-request'` message.\n *\n * #### Notes\n * For widgets with a layout, this message will inform the layout to\n * recalculate its size constraints to fit the space requirements of\n * its child widgets, and to update their position and size. Not all\n * layouts will respond to messages of this type.\n */\n Msg.FitRequest = new ConflatableMessage('fit-request');\n /**\n * A singleton conflatable `'activate-request'` message.\n *\n * #### Notes\n * This message should be dispatched to a widget when it should\n * perform the actions necessary to activate the widget, which\n * may include focusing its node or descendant node.\n */\n Msg.ActivateRequest = new ConflatableMessage('activate-request');\n /**\n * A singleton conflatable `'close-request'` message.\n *\n * #### Notes\n * This message should be dispatched to a widget when it should close\n * and remove itself from the widget hierarchy.\n */\n Msg.CloseRequest = new ConflatableMessage('close-request');\n })(Widget.Msg || (Widget.Msg = {}));\n /**\n * A message class for child related messages.\n */\n class ChildMessage extends Message {\n /**\n * Construct a new child message.\n *\n * @param type - The message type.\n *\n * @param child - The child widget for the message.\n */\n constructor(type, child) {\n super(type);\n this.child = child;\n }\n }\n Widget.ChildMessage = ChildMessage;\n /**\n * A message class for `'resize'` messages.\n */\n class ResizeMessage extends Message {\n /**\n * Construct a new resize message.\n *\n * @param width - The **offset width** of the widget, or `-1` if\n * the width is not known.\n *\n * @param height - The **offset height** of the widget, or `-1` if\n * the height is not known.\n */\n constructor(width, height) {\n super('resize');\n this.width = width;\n this.height = height;\n }\n }\n Widget.ResizeMessage = ResizeMessage;\n /**\n * The namespace for the `ResizeMessage` class statics.\n */\n (function (ResizeMessage) {\n /**\n * A singleton `'resize'` message with an unknown size.\n */\n ResizeMessage.UnknownSize = new ResizeMessage(-1, -1);\n })(ResizeMessage = Widget.ResizeMessage || (Widget.ResizeMessage = {}));\n /**\n * Attach a widget to a host DOM node.\n *\n * @param widget - The widget of interest.\n *\n * @param host - The DOM node to use as the widget's host.\n *\n * @param ref - The child of `host` to use as the reference element.\n * If this is provided, the widget will be inserted before this\n * node in the host. The default is `null`, which will cause the\n * widget to be added as the last child of the host.\n *\n * #### Notes\n * This will throw an error if the widget is not a root widget, if\n * the widget is already attached, or if the host is not attached\n * to the DOM.\n */\n function attach(widget, host, ref = null) {\n if (widget.parent) {\n throw new Error('Cannot attach a child widget.');\n }\n if (widget.isAttached || widget.node.isConnected) {\n throw new Error('Widget is already attached.');\n }\n if (!host.isConnected) {\n throw new Error('Host is not attached.');\n }\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n host.insertBefore(widget.node, ref);\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n Widget.attach = attach;\n /**\n * Detach the widget from its host DOM node.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * This will throw an error if the widget is not a root widget,\n * or if the widget is not attached to the DOM.\n */\n function detach(widget) {\n if (widget.parent) {\n throw new Error('Cannot detach a child widget.');\n }\n if (!widget.isAttached || !widget.node.isConnected) {\n throw new Error('Widget is not attached.');\n }\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n widget.node.parentNode.removeChild(widget.node);\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n Widget.detach = detach;\n})(Widget || (Widget = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$j;\n(function (Private) {\n /**\n * An attached property for the widget title object.\n */\n Private.titleProperty = new AttachedProperty({\n name: 'title',\n create: owner => new Title({ owner })\n });\n /**\n * Create a DOM node for the given widget options.\n */\n function createNode(options) {\n return options.node || document.createElement(options.tag || 'div');\n }\n Private.createNode = createNode;\n})(Private$j || (Private$j = {}));\n\n/**\n * An abstract base class for creating lumino layouts.\n *\n * #### Notes\n * A layout is used to add widgets to a parent and to arrange those\n * widgets within the parent's DOM node.\n *\n * This class implements the base functionality which is required of\n * nearly all layouts. It must be subclassed in order to be useful.\n *\n * Notably, this class does not define a uniform interface for adding\n * widgets to the layout. A subclass should define that API in a way\n * which is meaningful for its intended use.\n */\nclass Layout {\n /**\n * Construct a new layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options = {}) {\n this._disposed = false;\n this._parent = null;\n this._fitPolicy = options.fitPolicy || 'set-min-size';\n }\n /**\n * Dispose of the resources held by the layout.\n *\n * #### Notes\n * This should be reimplemented to clear and dispose of the widgets.\n *\n * All reimplementations should call the superclass method.\n *\n * This method is called automatically when the parent is disposed.\n */\n dispose() {\n this._parent = null;\n this._disposed = true;\n Signal.clearData(this);\n AttachedProperty.clearData(this);\n }\n /**\n * Test whether the layout is disposed.\n */\n get isDisposed() {\n return this._disposed;\n }\n /**\n * Get the parent widget of the layout.\n */\n get parent() {\n return this._parent;\n }\n /**\n * Set the parent widget of the layout.\n *\n * #### Notes\n * This is set automatically when installing the layout on the parent\n * widget. The parent widget should not be set directly by user code.\n */\n set parent(value) {\n if (this._parent === value) {\n return;\n }\n if (this._parent) {\n throw new Error('Cannot change parent widget.');\n }\n if (value.layout !== this) {\n throw new Error('Invalid parent widget.');\n }\n this._parent = value;\n this.init();\n }\n /**\n * Get the fit policy for the layout.\n *\n * #### Notes\n * The fit policy controls the computed size constraints which are\n * applied to the parent widget by the layout.\n *\n * Some layout implementations may ignore the fit policy.\n */\n get fitPolicy() {\n return this._fitPolicy;\n }\n /**\n * Set the fit policy for the layout.\n *\n * #### Notes\n * The fit policy controls the computed size constraints which are\n * applied to the parent widget by the layout.\n *\n * Some layout implementations may ignore the fit policy.\n *\n * Changing the fit policy will clear the current size constraint\n * for the parent widget and then re-fit the parent.\n */\n set fitPolicy(value) {\n // Bail if the policy does not change\n if (this._fitPolicy === value) {\n return;\n }\n // Update the internal policy.\n this._fitPolicy = value;\n // Clear the size constraints and schedule a fit of the parent.\n if (this._parent) {\n let style = this._parent.node.style;\n style.minWidth = '';\n style.minHeight = '';\n style.maxWidth = '';\n style.maxHeight = '';\n this._parent.fit();\n }\n }\n /**\n * Process a message sent to the parent widget.\n *\n * @param msg - The message sent to the parent widget.\n *\n * #### Notes\n * This method is called by the parent widget to process a message.\n *\n * Subclasses may reimplement this method as needed.\n */\n processParentMessage(msg) {\n switch (msg.type) {\n case 'resize':\n this.onResize(msg);\n break;\n case 'update-request':\n this.onUpdateRequest(msg);\n break;\n case 'fit-request':\n this.onFitRequest(msg);\n break;\n case 'before-show':\n this.onBeforeShow(msg);\n break;\n case 'after-show':\n this.onAfterShow(msg);\n break;\n case 'before-hide':\n this.onBeforeHide(msg);\n break;\n case 'after-hide':\n this.onAfterHide(msg);\n break;\n case 'before-attach':\n this.onBeforeAttach(msg);\n break;\n case 'after-attach':\n this.onAfterAttach(msg);\n break;\n case 'before-detach':\n this.onBeforeDetach(msg);\n break;\n case 'after-detach':\n this.onAfterDetach(msg);\n break;\n case 'child-removed':\n this.onChildRemoved(msg);\n break;\n case 'child-shown':\n this.onChildShown(msg);\n break;\n case 'child-hidden':\n this.onChildHidden(msg);\n break;\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n *\n * #### Notes\n * This method is invoked immediately after the layout is installed\n * on the parent widget.\n *\n * The default implementation reparents all of the widgets to the\n * layout parent widget.\n *\n * Subclasses should reimplement this method and attach the child\n * widget nodes to the parent widget's node.\n */\n init() {\n for (const widget of this) {\n widget.parent = this.parent;\n }\n }\n /**\n * A message handler invoked on a `'resize'` message.\n *\n * #### Notes\n * The layout should ensure that its widgets are resized according\n * to the specified layout space, and that they are sent a `'resize'`\n * message if appropriate.\n *\n * The default implementation of this method sends an `UnknownSize`\n * resize message to all widgets.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onResize(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, Widget.ResizeMessage.UnknownSize);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n *\n * #### Notes\n * The layout should ensure that its widgets are resized according\n * to the available layout space, and that they are sent a `'resize'`\n * message if appropriate.\n *\n * The default implementation of this method sends an `UnknownSize`\n * resize message to all widgets.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onUpdateRequest(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, Widget.ResizeMessage.UnknownSize);\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeAttach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on an `'after-attach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterAttach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on a `'before-detach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeDetach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message\n * to all widgets. It assumes all widget nodes are attached to the\n * parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterDetach(msg) {\n for (const widget of this) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeShow(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on an `'after-show'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterShow(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on a `'before-hide'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onBeforeHide(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on an `'after-hide'` message.\n *\n * #### Notes\n * The default implementation of this method forwards the message to\n * all non-hidden widgets. It assumes all widget nodes are attached\n * to the parent widget node.\n *\n * This may be reimplemented by subclasses as needed.\n */\n onAfterHide(msg) {\n for (const widget of this) {\n if (!widget.isHidden) {\n MessageLoop.sendMessage(widget, msg);\n }\n }\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n *\n * #### Notes\n * This will remove the child widget from the layout.\n *\n * Subclasses should **not** typically reimplement this method.\n */\n onChildRemoved(msg) {\n this.removeWidget(msg.child);\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onFitRequest(msg) { }\n /**\n * A message handler invoked on a `'child-shown'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildShown(msg) { }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n *\n * #### Notes\n * The default implementation of this handler is a no-op.\n */\n onChildHidden(msg) { }\n}\n/**\n * The namespace for the `Layout` class statics.\n */\n(function (Layout) {\n /**\n * Get the horizontal alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The horizontal alignment for the widget.\n *\n * #### Notes\n * If the layout width allocated to a widget is larger than its max\n * width, the horizontal alignment controls how the widget is placed\n * within the extra horizontal space.\n *\n * If the allocated width is less than the widget's max width, the\n * horizontal alignment has no effect.\n *\n * Some layout implementations may ignore horizontal alignment.\n */\n function getHorizontalAlignment(widget) {\n return Private$i.horizontalAlignmentProperty.get(widget);\n }\n Layout.getHorizontalAlignment = getHorizontalAlignment;\n /**\n * Set the horizontal alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the horizontal alignment.\n *\n * #### Notes\n * If the layout width allocated to a widget is larger than its max\n * width, the horizontal alignment controls how the widget is placed\n * within the extra horizontal space.\n *\n * If the allocated width is less than the widget's max width, the\n * horizontal alignment has no effect.\n *\n * Some layout implementations may ignore horizontal alignment.\n *\n * Changing the horizontal alignment will post an `update-request`\n * message to widget's parent, provided the parent has a layout\n * installed.\n */\n function setHorizontalAlignment(widget, value) {\n Private$i.horizontalAlignmentProperty.set(widget, value);\n }\n Layout.setHorizontalAlignment = setHorizontalAlignment;\n /**\n * Get the vertical alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The vertical alignment for the widget.\n *\n * #### Notes\n * If the layout height allocated to a widget is larger than its max\n * height, the vertical alignment controls how the widget is placed\n * within the extra vertical space.\n *\n * If the allocated height is less than the widget's max height, the\n * vertical alignment has no effect.\n *\n * Some layout implementations may ignore vertical alignment.\n */\n function getVerticalAlignment(widget) {\n return Private$i.verticalAlignmentProperty.get(widget);\n }\n Layout.getVerticalAlignment = getVerticalAlignment;\n /**\n * Set the vertical alignment for a widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the vertical alignment.\n *\n * #### Notes\n * If the layout height allocated to a widget is larger than its max\n * height, the vertical alignment controls how the widget is placed\n * within the extra vertical space.\n *\n * If the allocated height is less than the widget's max height, the\n * vertical alignment has no effect.\n *\n * Some layout implementations may ignore vertical alignment.\n *\n * Changing the horizontal alignment will post an `update-request`\n * message to widget's parent, provided the parent has a layout\n * installed.\n */\n function setVerticalAlignment(widget, value) {\n Private$i.verticalAlignmentProperty.set(widget, value);\n }\n Layout.setVerticalAlignment = setVerticalAlignment;\n})(Layout || (Layout = {}));\n/**\n * An object which assists in the absolute layout of widgets.\n *\n * #### Notes\n * This class is useful when implementing a layout which arranges its\n * widgets using absolute positioning.\n *\n * This class is used by nearly all of the built-in lumino layouts.\n */\nclass LayoutItem {\n /**\n * Construct a new layout item.\n *\n * @param widget - The widget to be managed by the item.\n *\n * #### Notes\n * The widget will be set to absolute positioning.\n * The widget will use strict CSS containment.\n */\n constructor(widget) {\n this._top = NaN;\n this._left = NaN;\n this._width = NaN;\n this._height = NaN;\n this._minWidth = 0;\n this._minHeight = 0;\n this._maxWidth = Infinity;\n this._maxHeight = Infinity;\n this._disposed = false;\n this.widget = widget;\n this.widget.node.style.position = 'absolute';\n this.widget.node.style.contain = 'strict';\n }\n /**\n * Dispose of the the layout item.\n *\n * #### Notes\n * This will reset the positioning of the widget.\n */\n dispose() {\n // Do nothing if the item is already disposed.\n if (this._disposed) {\n return;\n }\n // Mark the item as disposed.\n this._disposed = true;\n // Reset the widget style.\n let style = this.widget.node.style;\n style.position = '';\n style.top = '';\n style.left = '';\n style.width = '';\n style.height = '';\n style.contain = '';\n }\n /**\n * The computed minimum width of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get minWidth() {\n return this._minWidth;\n }\n /**\n * The computed minimum height of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get minHeight() {\n return this._minHeight;\n }\n /**\n * The computed maximum width of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get maxWidth() {\n return this._maxWidth;\n }\n /**\n * The computed maximum height of the widget.\n *\n * #### Notes\n * This value can be updated by calling the `fit` method.\n */\n get maxHeight() {\n return this._maxHeight;\n }\n /**\n * Whether the layout item is disposed.\n */\n get isDisposed() {\n return this._disposed;\n }\n /**\n * Whether the managed widget is hidden.\n */\n get isHidden() {\n return this.widget.isHidden;\n }\n /**\n * Whether the managed widget is visible.\n */\n get isVisible() {\n return this.widget.isVisible;\n }\n /**\n * Whether the managed widget is attached.\n */\n get isAttached() {\n return this.widget.isAttached;\n }\n /**\n * Update the computed size limits of the managed widget.\n */\n fit() {\n let limits = ElementExt.sizeLimits(this.widget.node);\n this._minWidth = limits.minWidth;\n this._minHeight = limits.minHeight;\n this._maxWidth = limits.maxWidth;\n this._maxHeight = limits.maxHeight;\n }\n /**\n * Update the position and size of the managed widget.\n *\n * @param left - The left edge position of the layout box.\n *\n * @param top - The top edge position of the layout box.\n *\n * @param width - The width of the layout box.\n *\n * @param height - The height of the layout box.\n */\n update(left, top, width, height) {\n // Clamp the size to the computed size limits.\n let clampW = Math.max(this._minWidth, Math.min(width, this._maxWidth));\n let clampH = Math.max(this._minHeight, Math.min(height, this._maxHeight));\n // Adjust the left edge for the horizontal alignment, if needed.\n if (clampW < width) {\n switch (Layout.getHorizontalAlignment(this.widget)) {\n case 'left':\n break;\n case 'center':\n left += (width - clampW) / 2;\n break;\n case 'right':\n left += width - clampW;\n break;\n default:\n throw 'unreachable';\n }\n }\n // Adjust the top edge for the vertical alignment, if needed.\n if (clampH < height) {\n switch (Layout.getVerticalAlignment(this.widget)) {\n case 'top':\n break;\n case 'center':\n top += (height - clampH) / 2;\n break;\n case 'bottom':\n top += height - clampH;\n break;\n default:\n throw 'unreachable';\n }\n }\n // Set up the resize variables.\n let resized = false;\n let style = this.widget.node.style;\n // Update the top edge of the widget if needed.\n if (this._top !== top) {\n this._top = top;\n style.top = `${top}px`;\n }\n // Update the left edge of the widget if needed.\n if (this._left !== left) {\n this._left = left;\n style.left = `${left}px`;\n }\n // Update the width of the widget if needed.\n if (this._width !== clampW) {\n resized = true;\n this._width = clampW;\n style.width = `${clampW}px`;\n }\n // Update the height of the widget if needed.\n if (this._height !== clampH) {\n resized = true;\n this._height = clampH;\n style.height = `${clampH}px`;\n }\n // Send a resize message to the widget if needed.\n if (resized) {\n let msg = new Widget.ResizeMessage(clampW, clampH);\n MessageLoop.sendMessage(this.widget, msg);\n }\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$i;\n(function (Private) {\n /**\n * The attached property for a widget horizontal alignment.\n */\n Private.horizontalAlignmentProperty = new AttachedProperty({\n name: 'horizontalAlignment',\n create: () => 'center',\n changed: onAlignmentChanged\n });\n /**\n * The attached property for a widget vertical alignment.\n */\n Private.verticalAlignmentProperty = new AttachedProperty({\n name: 'verticalAlignment',\n create: () => 'top',\n changed: onAlignmentChanged\n });\n /**\n * The change handler for the attached alignment properties.\n */\n function onAlignmentChanged(child) {\n if (child.parent && child.parent.layout) {\n child.parent.update();\n }\n }\n})(Private$i || (Private$i = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A concrete layout implementation suitable for many use cases.\n *\n * #### Notes\n * This class is suitable as a base class for implementing a variety of\n * layouts, but can also be used directly with standard CSS to layout a\n * collection of widgets.\n */\nclass PanelLayout extends Layout {\n constructor() {\n super(...arguments);\n this._widgets = [];\n }\n /**\n * Dispose of the resources held by the layout.\n *\n * #### Notes\n * This will clear and dispose all widgets in the layout.\n *\n * All reimplementations should call the superclass method.\n *\n * This method is called automatically when the parent is disposed.\n */\n dispose() {\n while (this._widgets.length > 0) {\n this._widgets.pop().dispose();\n }\n super.dispose();\n }\n /**\n * A read-only array of the widgets in the layout.\n */\n get widgets() {\n return this._widgets;\n }\n /**\n * Create an iterator over the widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n */\n *[Symbol.iterator]() {\n yield* this._widgets;\n }\n /**\n * Add a widget to the end of the layout.\n *\n * @param widget - The widget to add to the layout.\n *\n * #### Notes\n * If the widget is already contained in the layout, it will be moved.\n */\n addWidget(widget) {\n this.insertWidget(this._widgets.length, widget);\n }\n /**\n * Insert a widget into the layout at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into the layout.\n *\n * #### Notes\n * The index will be clamped to the bounds of the widgets.\n *\n * If the widget is already added to the layout, it will be moved.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n */\n insertWidget(index, widget) {\n // Remove the widget from its current parent. This is a no-op\n // if the widget's parent is already the layout parent widget.\n widget.parent = this.parent;\n // Look up the current index of the widget.\n let i = this._widgets.indexOf(widget);\n // Clamp the insert index to the array bounds.\n let j = Math.max(0, Math.min(index, this._widgets.length));\n // If the widget is not in the array, insert it.\n if (i === -1) {\n // Insert the widget into the array.\n ArrayExt.insert(this._widgets, j, widget);\n // If the layout is parented, attach the widget to the DOM.\n if (this.parent) {\n this.attachWidget(j, widget);\n }\n // There is nothing more to do.\n return;\n }\n // Otherwise, the widget exists in the array and should be moved.\n // Adjust the index if the location is at the end of the array.\n if (j === this._widgets.length) {\n j--;\n }\n // Bail if there is no effective move.\n if (i === j) {\n return;\n }\n // Move the widget to the new location.\n ArrayExt.move(this._widgets, i, j);\n // If the layout is parented, move the widget in the DOM.\n if (this.parent) {\n this.moveWidget(i, j, widget);\n }\n }\n /**\n * Remove a widget from the layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n this.removeWidgetAt(this._widgets.indexOf(widget));\n }\n /**\n * Remove the widget at a given index from the layout.\n *\n * @param index - The index of the widget to remove.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n */\n removeWidgetAt(index) {\n // Remove the widget from the array.\n let widget = ArrayExt.removeAt(this._widgets, index);\n // If the layout is parented, detach the widget from the DOM.\n if (widget && this.parent) {\n this.detachWidget(index, widget);\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n super.init();\n let index = 0;\n for (const widget of this) {\n this.attachWidget(index++, widget);\n }\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This method is called automatically by the panel layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation adds the widgets's node to the parent's\n * node at the proper location, and sends the appropriate attach\n * messages to the widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is added to the parent's node.\n */\n attachWidget(index, widget) {\n // Look up the next sibling reference node.\n let ref = this.parent.node.children[index];\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Insert the widget's node before the sibling.\n this.parent.node.insertBefore(widget.node, ref);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This method is called automatically by the panel layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation moves the widget's node to the proper\n * location in the parent's node and sends the appropriate attach and\n * detach messages to the widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is moved in the parent's node.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` and message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Look up the next sibling reference node.\n let ref = this.parent.node.children[toIndex];\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Insert the widget's node before the sibling.\n this.parent.node.insertBefore(widget.node, ref);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This method is called automatically by the panel layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation removes the widget's node from the\n * parent's node, and sends the appropriate detach messages to the\n * widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is removed from the parent's node.\n */\n detachWidget(index, widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n }\n}\n\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\nvar Utils;\n(function (Utils) {\n /**\n * Clamp a dimension value to an integer >= 0.\n */\n function clampDimension(value) {\n return Math.max(0, Math.floor(value));\n }\n Utils.clampDimension = clampDimension;\n})(Utils || (Utils = {}));\nvar Utils$1 = Utils;\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which arranges its widgets into resizable sections.\n */\nclass SplitLayout extends PanelLayout {\n /**\n * Construct a new split layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options) {\n super();\n this.widgetOffset = 0;\n this._fixed = 0;\n this._spacing = 4;\n this._dirty = false;\n this._hasNormedSizes = false;\n this._sizers = [];\n this._items = [];\n this._handles = [];\n this._box = null;\n this._alignment = 'start';\n this._orientation = 'horizontal';\n this.renderer = options.renderer;\n if (options.orientation !== undefined) {\n this._orientation = options.orientation;\n }\n if (options.alignment !== undefined) {\n this._alignment = options.alignment;\n }\n if (options.spacing !== undefined) {\n this._spacing = Utils.clampDimension(options.spacing);\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the layout items.\n for (const item of this._items) {\n item.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n this._sizers.length = 0;\n this._handles.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Get the layout orientation for the split layout.\n */\n get orientation() {\n return this._orientation;\n }\n /**\n * Set the layout orientation for the split layout.\n */\n set orientation(value) {\n if (this._orientation === value) {\n return;\n }\n this._orientation = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['orientation'] = value;\n this.parent.fit();\n }\n /**\n * Get the content alignment for the split layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split layout.\n */\n get alignment() {\n return this._alignment;\n }\n /**\n * Set the content alignment for the split layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split layout.\n */\n set alignment(value) {\n if (this._alignment === value) {\n return;\n }\n this._alignment = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['alignment'] = value;\n this.parent.update();\n }\n /**\n * Get the inter-element spacing for the split layout.\n */\n get spacing() {\n return this._spacing;\n }\n /**\n * Set the inter-element spacing for the split layout.\n */\n set spacing(value) {\n value = Utils.clampDimension(value);\n if (this._spacing === value) {\n return;\n }\n this._spacing = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * A read-only array of the split handles in the layout.\n */\n get handles() {\n return this._handles;\n }\n /**\n * Get the absolute sizes of the widgets in the layout.\n *\n * @returns A new array of the absolute sizes of the widgets.\n *\n * This method **does not** measure the DOM nodes.\n */\n absoluteSizes() {\n return this._sizers.map(sizer => sizer.size);\n }\n /**\n * Get the relative sizes of the widgets in the layout.\n *\n * @returns A new array of the relative sizes of the widgets.\n *\n * #### Notes\n * The returned sizes reflect the sizes of the widgets normalized\n * relative to their siblings.\n *\n * This method **does not** measure the DOM nodes.\n */\n relativeSizes() {\n return Private$h.normalize(this._sizers.map(sizer => sizer.size));\n }\n /**\n * Set the relative sizes for the widgets in the layout.\n *\n * @param sizes - The relative sizes for the widgets in the panel.\n * @param update - Update the layout after setting relative sizes.\n * Default is True.\n *\n * #### Notes\n * Extra values are ignored, too few will yield an undefined layout.\n *\n * The actual geometry of the DOM nodes is updated asynchronously.\n */\n setRelativeSizes(sizes, update = true) {\n // Copy the sizes and pad with zeros as needed.\n let n = this._sizers.length;\n let temp = sizes.slice(0, n);\n while (temp.length < n) {\n temp.push(0);\n }\n // Normalize the padded sizes.\n let normed = Private$h.normalize(temp);\n // Apply the normalized sizes to the sizers.\n for (let i = 0; i < n; ++i) {\n let sizer = this._sizers[i];\n sizer.sizeHint = normed[i];\n sizer.size = normed[i];\n }\n // Set the flag indicating the sizes are normalized.\n this._hasNormedSizes = true;\n // Trigger an update of the parent widget.\n if (update && this.parent) {\n this.parent.update();\n }\n }\n /**\n * Move the offset position of a split handle.\n *\n * @param index - The index of the handle of the interest.\n *\n * @param position - The desired offset position of the handle.\n *\n * #### Notes\n * The position is relative to the offset parent.\n *\n * This will move the handle as close as possible to the desired\n * position. The sibling widgets will be adjusted as necessary.\n */\n moveHandle(index, position) {\n // Bail if the index is invalid or the handle is hidden.\n let handle = this._handles[index];\n if (!handle || handle.classList.contains('lm-mod-hidden')) {\n return;\n }\n // Compute the desired delta movement for the handle.\n let delta;\n if (this._orientation === 'horizontal') {\n delta = position - handle.offsetLeft;\n }\n else {\n delta = position - handle.offsetTop;\n }\n // Bail if there is no handle movement.\n if (delta === 0) {\n return;\n }\n // Prevent widget resizing unless needed.\n for (let sizer of this._sizers) {\n if (sizer.size > 0) {\n sizer.sizeHint = sizer.size;\n }\n }\n // Adjust the sizers to reflect the handle movement.\n BoxEngine.adjust(this._sizers, index, delta);\n // Update the layout of the widgets.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n this.parent.dataset['orientation'] = this.orientation;\n this.parent.dataset['alignment'] = this.alignment;\n super.init();\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n attachWidget(index, widget) {\n // Create the item, handle, and sizer for the new widget.\n let item = new LayoutItem(widget);\n let handle = Private$h.createHandle(this.renderer);\n let average = Private$h.averageSize(this._sizers);\n let sizer = Private$h.createSizer(average);\n // Insert the item, handle, and sizer into the internal arrays.\n ArrayExt.insert(this._items, index, item);\n ArrayExt.insert(this._sizers, index, sizer);\n ArrayExt.insert(this._handles, index, handle);\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget and handle nodes to the parent.\n this.parent.node.appendChild(widget.node);\n this.parent.node.appendChild(handle);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Move the item, sizer, and handle for the widget.\n ArrayExt.move(this._items, fromIndex, toIndex);\n ArrayExt.move(this._sizers, fromIndex, toIndex);\n ArrayExt.move(this._handles, fromIndex, toIndex);\n // Post a fit request to the parent to show/hide last handle.\n this.parent.fit();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n // Remove the item, handle, and sizer for the widget.\n let item = ArrayExt.removeAt(this._items, index);\n let handle = ArrayExt.removeAt(this._handles, index);\n ArrayExt.removeAt(this._sizers, index);\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget and handle nodes from the parent.\n this.parent.node.removeChild(widget.node);\n this.parent.node.removeChild(handle);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Dispose of the layout item.\n item.dispose();\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Update the item position.\n *\n * @param i Item index\n * @param isHorizontal Whether the layout is horizontal or not\n * @param left Left position in pixels\n * @param top Top position in pixels\n * @param height Item height\n * @param width Item width\n * @param size Item size\n */\n updateItemPosition(i, isHorizontal, left, top, height, width, size) {\n const item = this._items[i];\n if (item.isHidden) {\n return;\n }\n // Fetch the style for the handle.\n let handleStyle = this._handles[i].style;\n // Update the widget and handle, and advance the relevant edge.\n if (isHorizontal) {\n left += this.widgetOffset;\n item.update(left, top, size, height);\n left += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${this._spacing}px`;\n handleStyle.height = `${height}px`;\n }\n else {\n top += this.widgetOffset;\n item.update(left, top, width, size);\n top += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${width}px`;\n handleStyle.height = `${this._spacing}px`;\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Update the handles and track the visible widget count.\n let nVisible = 0;\n let lastHandleIndex = -1;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n if (this._items[i].isHidden) {\n this._handles[i].classList.add('lm-mod-hidden');\n }\n else {\n this._handles[i].classList.remove('lm-mod-hidden');\n lastHandleIndex = i;\n nVisible++;\n }\n }\n // Hide the handle for the last visible widget.\n if (lastHandleIndex !== -1) {\n this._handles[lastHandleIndex].classList.add('lm-mod-hidden');\n }\n // Update the fixed space for the visible items.\n this._fixed =\n this._spacing * Math.max(0, nVisible - 1) +\n this.widgetOffset * this._items.length;\n // Setup the computed minimum size.\n let horz = this._orientation === 'horizontal';\n let minW = horz ? this._fixed : 0;\n let minH = horz ? 0 : this._fixed;\n // Update the sizers and computed size limits.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item and corresponding box sizer.\n let item = this._items[i];\n let sizer = this._sizers[i];\n // Prevent resizing unless necessary.\n if (sizer.size > 0) {\n sizer.sizeHint = sizer.size;\n }\n // If the item is hidden, it should consume zero size.\n if (item.isHidden) {\n sizer.minSize = 0;\n sizer.maxSize = 0;\n continue;\n }\n // Update the size limits for the item.\n item.fit();\n // Update the stretch factor.\n sizer.stretch = SplitLayout.getStretch(item.widget);\n // Update the sizer limits and computed min size.\n if (horz) {\n sizer.minSize = item.minWidth;\n sizer.maxSize = item.maxWidth;\n minW += item.minWidth;\n minH = Math.max(minH, item.minHeight);\n }\n else {\n sizer.minSize = item.minHeight;\n sizer.maxSize = item.maxHeight;\n minH += item.minHeight;\n minW = Math.max(minW, item.minWidth);\n }\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Bail early if there are no visible items to layout.\n if (nVisible === 0 && this.widgetOffset === 0) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the actual layout bounds adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Set up the variables for justification and alignment offset.\n let extra = 0;\n let offset = 0;\n let horz = this._orientation === 'horizontal';\n if (nVisible > 0) {\n // Compute the adjusted layout space.\n let space;\n if (horz) {\n // left += this.widgetOffset;\n space = Math.max(0, width - this._fixed);\n }\n else {\n // top += this.widgetOffset;\n space = Math.max(0, height - this._fixed);\n }\n // Scale the size hints if they are normalized.\n if (this._hasNormedSizes) {\n for (let sizer of this._sizers) {\n sizer.sizeHint *= space;\n }\n this._hasNormedSizes = false;\n }\n // Distribute the layout space to the box sizers.\n let delta = BoxEngine.calc(this._sizers, space);\n // Account for alignment if there is extra layout space.\n if (delta > 0) {\n switch (this._alignment) {\n case 'start':\n break;\n case 'center':\n extra = 0;\n offset = delta / 2;\n break;\n case 'end':\n extra = 0;\n offset = delta;\n break;\n case 'justify':\n extra = delta / nVisible;\n offset = 0;\n break;\n default:\n throw 'unreachable';\n }\n }\n }\n // Layout the items using the computed box sizes.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n const item = this._items[i];\n // Fetch the computed size for the widget.\n const size = item.isHidden ? 0 : this._sizers[i].size + extra;\n this.updateItemPosition(i, horz, horz ? left + offset : left, horz ? top : top + offset, height, width, size);\n const fullOffset = this.widgetOffset +\n (this._handles[i].classList.contains('lm-mod-hidden')\n ? 0\n : this._spacing);\n if (horz) {\n left += size + fullOffset;\n }\n else {\n top += size + fullOffset;\n }\n }\n }\n}\n/**\n * The namespace for the `SplitLayout` class statics.\n */\n(function (SplitLayout) {\n /**\n * Get the split layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The split layout stretch factor for the widget.\n */\n function getStretch(widget) {\n return Private$h.stretchProperty.get(widget);\n }\n SplitLayout.getStretch = getStretch;\n /**\n * Set the split layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n Private$h.stretchProperty.set(widget, value);\n }\n SplitLayout.setStretch = setStretch;\n})(SplitLayout || (SplitLayout = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$h;\n(function (Private) {\n /**\n * The property descriptor for a widget stretch factor.\n */\n Private.stretchProperty = new AttachedProperty({\n name: 'stretch',\n create: () => 0,\n coerce: (owner, value) => Math.max(0, Math.floor(value)),\n changed: onChildSizingChanged\n });\n /**\n * Create a new box sizer with the given size hint.\n */\n function createSizer(size) {\n let sizer = new BoxSizer();\n sizer.sizeHint = Math.floor(size);\n return sizer;\n }\n Private.createSizer = createSizer;\n /**\n * Create a new split handle node using the given renderer.\n */\n function createHandle(renderer) {\n let handle = renderer.createHandle();\n handle.style.position = 'absolute';\n // Do not use size containment to allow the handle to fill the available space\n handle.style.contain = 'style';\n return handle;\n }\n Private.createHandle = createHandle;\n /**\n * Compute the average size of an array of box sizers.\n */\n function averageSize(sizers) {\n return sizers.reduce((v, s) => v + s.size, 0) / sizers.length || 0;\n }\n Private.averageSize = averageSize;\n /**\n * Normalize an array of values.\n */\n function normalize(values) {\n let n = values.length;\n if (n === 0) {\n return [];\n }\n let sum = values.reduce((a, b) => a + Math.abs(b), 0);\n return sum === 0 ? values.map(v => 1 / n) : values.map(v => v / sum);\n }\n Private.normalize = normalize;\n /**\n * The change handler for the attached sizing properties.\n */\n function onChildSizingChanged(child) {\n if (child.parent && child.parent.layout instanceof SplitLayout) {\n child.parent.fit();\n }\n }\n})(Private$h || (Private$h = {}));\n\n/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n/**\n * A layout which arranges its widgets into collapsible resizable sections.\n */\nclass AccordionLayout extends SplitLayout {\n /**\n * Construct a new accordion layout.\n *\n * @param options - The options for initializing the layout.\n *\n * #### Notes\n * The default orientation will be vertical.\n *\n * Titles must be rotated for horizontal accordion panel using CSS: see accordionpanel.css\n */\n constructor(options) {\n super({ ...options, orientation: options.orientation || 'vertical' });\n this._titles = [];\n this.titleSpace = options.titleSpace || 22;\n }\n /**\n * The section title height or width depending on the orientation.\n */\n get titleSpace() {\n return this.widgetOffset;\n }\n set titleSpace(value) {\n value = Utils$1.clampDimension(value);\n if (this.widgetOffset === value) {\n return;\n }\n this.widgetOffset = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * A read-only array of the section titles in the panel.\n */\n get titles() {\n return this._titles;\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n // Clear the layout state.\n this._titles.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n updateTitle(index, widget) {\n const oldTitle = this._titles[index];\n const expanded = oldTitle.classList.contains('lm-mod-expanded');\n const newTitle = Private$g.createTitle(this.renderer, widget.title, expanded);\n this._titles[index] = newTitle;\n // Add the title node to the parent before the widget.\n this.parent.node.replaceChild(newTitle, oldTitle);\n }\n /**\n * Insert a widget into the layout at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into the layout.\n *\n * #### Notes\n * The index will be clamped to the bounds of the widgets.\n *\n * If the widget is already added to the layout, it will be moved.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n */\n insertWidget(index, widget) {\n if (!widget.id) {\n widget.id = `id-${UUID.uuid4()}`;\n }\n super.insertWidget(index, widget);\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n */\n attachWidget(index, widget) {\n const title = Private$g.createTitle(this.renderer, widget.title);\n ArrayExt.insert(this._titles, index, title);\n // Add the title node to the parent before the widget.\n this.parent.node.appendChild(title);\n widget.node.setAttribute('role', 'region');\n widget.node.setAttribute('aria-labelledby', title.id);\n super.attachWidget(index, widget);\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n */\n moveWidget(fromIndex, toIndex, widget) {\n ArrayExt.move(this._titles, fromIndex, toIndex);\n super.moveWidget(fromIndex, toIndex, widget);\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n const title = ArrayExt.removeAt(this._titles, index);\n this.parent.node.removeChild(title);\n super.detachWidget(index, widget);\n }\n /**\n * Update the item position.\n *\n * @param i Item index\n * @param isHorizontal Whether the layout is horizontal or not\n * @param left Left position in pixels\n * @param top Top position in pixels\n * @param height Item height\n * @param width Item width\n * @param size Item size\n */\n updateItemPosition(i, isHorizontal, left, top, height, width, size) {\n const titleStyle = this._titles[i].style;\n // Titles must be rotated for horizontal accordion panel using CSS: see accordionpanel.css\n titleStyle.top = `${top}px`;\n titleStyle.left = `${left}px`;\n titleStyle.height = `${this.widgetOffset}px`;\n if (isHorizontal) {\n titleStyle.width = `${height}px`;\n }\n else {\n titleStyle.width = `${width}px`;\n }\n super.updateItemPosition(i, isHorizontal, left, top, height, width, size);\n }\n}\nvar Private$g;\n(function (Private) {\n /**\n * Create the title HTML element.\n *\n * @param renderer Accordion renderer\n * @param data Widget title\n * @returns Title HTML element\n */\n function createTitle(renderer, data, expanded = true) {\n const title = renderer.createSectionTitle(data);\n title.style.position = 'absolute';\n title.style.contain = 'strict';\n title.setAttribute('aria-label', `${data.label} Section`);\n title.setAttribute('aria-expanded', expanded ? 'true' : 'false');\n title.setAttribute('aria-controls', data.owner.id);\n if (expanded) {\n title.classList.add('lm-mod-expanded');\n }\n return title;\n }\n Private.createTitle = createTitle;\n})(Private$g || (Private$g = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A simple and convenient panel widget class.\n *\n * #### Notes\n * This class is suitable as a base class for implementing a variety of\n * convenience panel widgets, but can also be used directly with CSS to\n * arrange a collection of widgets.\n *\n * This class provides a convenience wrapper around a {@link PanelLayout}.\n */\nclass Panel extends Widget {\n /**\n * Construct a new panel.\n *\n * @param options - The options for initializing the panel.\n */\n constructor(options = {}) {\n super();\n this.addClass('lm-Panel');\n this.layout = Private$f.createLayout(options);\n }\n /**\n * A read-only array of the widgets in the panel.\n */\n get widgets() {\n return this.layout.widgets;\n }\n /**\n * Add a widget to the end of the panel.\n *\n * @param widget - The widget to add to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n addWidget(widget) {\n this.layout.addWidget(widget);\n }\n /**\n * Insert a widget at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n insertWidget(index, widget) {\n this.layout.insertWidget(index, widget);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$f;\n(function (Private) {\n /**\n * Create a panel layout for the given panel options.\n */\n function createLayout(options) {\n return options.layout || new PanelLayout();\n }\n Private.createLayout = createLayout;\n})(Private$f || (Private$f = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A panel which arranges its widgets into resizable sections.\n *\n * #### Notes\n * This class provides a convenience wrapper around a {@link SplitLayout}.\n */\nclass SplitPanel extends Panel {\n /**\n * Construct a new split panel.\n *\n * @param options - The options for initializing the split panel.\n */\n constructor(options = {}) {\n super({ layout: Private$e.createLayout(options) });\n this._handleMoved = new Signal(this);\n this._pressData = null;\n this.addClass('lm-SplitPanel');\n }\n /**\n * Dispose of the resources held by the panel.\n */\n dispose() {\n this._releaseMouse();\n super.dispose();\n }\n /**\n * Get the layout orientation for the split panel.\n */\n get orientation() {\n return this.layout.orientation;\n }\n /**\n * Set the layout orientation for the split panel.\n */\n set orientation(value) {\n this.layout.orientation = value;\n }\n /**\n * Get the content alignment for the split panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split panel.\n */\n get alignment() {\n return this.layout.alignment;\n }\n /**\n * Set the content alignment for the split panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire split panel.\n */\n set alignment(value) {\n this.layout.alignment = value;\n }\n /**\n * Get the inter-element spacing for the split panel.\n */\n get spacing() {\n return this.layout.spacing;\n }\n /**\n * Set the inter-element spacing for the split panel.\n */\n set spacing(value) {\n this.layout.spacing = value;\n }\n /**\n * The renderer used by the split panel.\n */\n get renderer() {\n return this.layout.renderer;\n }\n /**\n * A signal emitted when a split handle has moved.\n */\n get handleMoved() {\n return this._handleMoved;\n }\n /**\n * A read-only array of the split handles in the panel.\n */\n get handles() {\n return this.layout.handles;\n }\n /**\n * Get the relative sizes of the widgets in the panel.\n *\n * @returns A new array of the relative sizes of the widgets.\n *\n * #### Notes\n * The returned sizes reflect the sizes of the widgets normalized\n * relative to their siblings.\n *\n * This method **does not** measure the DOM nodes.\n */\n relativeSizes() {\n return this.layout.relativeSizes();\n }\n /**\n * Set the relative sizes for the widgets in the panel.\n *\n * @param sizes - The relative sizes for the widgets in the panel.\n * @param update - Update the layout after setting relative sizes.\n * Default is True.\n *\n * #### Notes\n * Extra values are ignored, too few will yield an undefined layout.\n *\n * The actual geometry of the DOM nodes is updated asynchronously.\n */\n setRelativeSizes(sizes, update = true) {\n this.layout.setRelativeSizes(sizes, update);\n }\n /**\n * Handle the DOM events for the split panel.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the panel's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'pointerdown':\n this._evtPointerDown(event);\n break;\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('pointerdown', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('pointerdown', this);\n this._releaseMouse();\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n msg.child.addClass('lm-SplitPanel-child');\n this._releaseMouse();\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n msg.child.removeClass('lm-SplitPanel-child');\n this._releaseMouse();\n }\n /**\n * Handle the `'keydown'` event for the split panel.\n */\n _evtKeyDown(event) {\n // Stop input events during drag.\n if (this._pressData) {\n event.preventDefault();\n event.stopPropagation();\n }\n // Release the mouse if `Escape` is pressed.\n if (event.keyCode === 27) {\n this._releaseMouse();\n }\n }\n /**\n * Handle the `'pointerdown'` event for the split panel.\n */\n _evtPointerDown(event) {\n // Do nothing if the primary button is not pressed.\n if (event.button !== 0) {\n return;\n }\n // Find the handle which contains the target, if any.\n let layout = this.layout;\n let index = ArrayExt.findFirstIndex(layout.handles, handle => {\n return handle.contains(event.target);\n });\n // Bail early if the mouse press was not on a handle.\n if (index === -1) {\n return;\n }\n // Stop the event when a split handle is pressed.\n event.preventDefault();\n event.stopPropagation();\n // Add the extra document listeners.\n document.addEventListener('pointerup', this, true);\n document.addEventListener('pointermove', this, true);\n document.addEventListener('keydown', this, true);\n document.addEventListener('contextmenu', this, true);\n // Compute the offset delta for the handle press.\n let delta;\n let handle = layout.handles[index];\n let rect = handle.getBoundingClientRect();\n if (layout.orientation === 'horizontal') {\n delta = event.clientX - rect.left;\n }\n else {\n delta = event.clientY - rect.top;\n }\n // Override the cursor and store the press data.\n let style = window.getComputedStyle(handle);\n let override = Drag.overrideCursor(style.cursor);\n this._pressData = { index, delta, override };\n }\n /**\n * Handle the `'pointermove'` event for the split panel.\n */\n _evtPointerMove(event) {\n // Stop the event when dragging a split handle.\n event.preventDefault();\n event.stopPropagation();\n // Compute the desired offset position for the handle.\n let pos;\n let layout = this.layout;\n let rect = this.node.getBoundingClientRect();\n if (layout.orientation === 'horizontal') {\n pos = event.clientX - rect.left - this._pressData.delta;\n }\n else {\n pos = event.clientY - rect.top - this._pressData.delta;\n }\n // Move the handle as close to the desired position as possible.\n layout.moveHandle(this._pressData.index, pos);\n }\n /**\n * Handle the `'pointerup'` event for the split panel.\n */\n _evtPointerUp(event) {\n // Do nothing if the primary button is not released.\n if (event.button !== 0) {\n return;\n }\n // Stop the event when releasing a handle.\n event.preventDefault();\n event.stopPropagation();\n // Finalize the mouse release.\n this._releaseMouse();\n }\n /**\n * Release the mouse grab for the split panel.\n */\n _releaseMouse() {\n // Bail early if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Clear the override cursor.\n this._pressData.override.dispose();\n this._pressData = null;\n // Emit the handle moved signal.\n this._handleMoved.emit();\n // Remove the extra document listeners.\n document.removeEventListener('keydown', this, true);\n document.removeEventListener('pointerup', this, true);\n document.removeEventListener('pointermove', this, true);\n document.removeEventListener('contextmenu', this, true);\n }\n}\n/**\n * The namespace for the `SplitPanel` class statics.\n */\n(function (SplitPanel) {\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer {\n /**\n * Create a new handle for use with a split panel.\n *\n * @returns A new handle element for a split panel.\n */\n createHandle() {\n let handle = document.createElement('div');\n handle.className = 'lm-SplitPanel-handle';\n return handle;\n }\n }\n SplitPanel.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n SplitPanel.defaultRenderer = new Renderer();\n /**\n * Get the split panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The split panel stretch factor for the widget.\n */\n function getStretch(widget) {\n return SplitLayout.getStretch(widget);\n }\n SplitPanel.getStretch = getStretch;\n /**\n * Set the split panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n SplitLayout.setStretch(widget, value);\n }\n SplitPanel.setStretch = setStretch;\n})(SplitPanel || (SplitPanel = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$e;\n(function (Private) {\n /**\n * Create a split layout for the given panel options.\n */\n function createLayout(options) {\n return (options.layout ||\n new SplitLayout({\n renderer: options.renderer || SplitPanel.defaultRenderer,\n orientation: options.orientation,\n alignment: options.alignment,\n spacing: options.spacing\n }));\n }\n Private.createLayout = createLayout;\n})(Private$e || (Private$e = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * A panel which arranges its widgets into resizable sections separated by a title widget.\n *\n * #### Notes\n * This class provides a convenience wrapper around {@link AccordionLayout}.\n */\nclass AccordionPanel extends SplitPanel {\n /**\n * Construct a new accordion panel.\n *\n * @param options - The options for initializing the accordion panel.\n */\n constructor(options = {}) {\n super({ ...options, layout: Private$d.createLayout(options) });\n this._widgetSizesCache = new WeakMap();\n this._expansionToggled = new Signal(this);\n this.addClass('lm-AccordionPanel');\n }\n /**\n * The renderer used by the accordion panel.\n */\n get renderer() {\n return this.layout.renderer;\n }\n /**\n * The section title space.\n *\n * This is the height if the panel is vertical and the width if it is\n * horizontal.\n */\n get titleSpace() {\n return this.layout.titleSpace;\n }\n set titleSpace(value) {\n this.layout.titleSpace = value;\n }\n /**\n * A read-only array of the section titles in the panel.\n */\n get titles() {\n return this.layout.titles;\n }\n /**\n * A signal emitted when a widget of the AccordionPanel is collapsed or expanded.\n */\n get expansionToggled() {\n return this._expansionToggled;\n }\n /**\n * Add a widget to the end of the panel.\n *\n * @param widget - The widget to add to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n addWidget(widget) {\n super.addWidget(widget);\n widget.title.changed.connect(this._onTitleChanged, this);\n }\n /**\n * Collapse the widget at position `index`.\n *\n * #### Notes\n * If no widget is found for `index`, this will bail.\n *\n * @param index Widget index\n */\n collapse(index) {\n const widget = this.layout.widgets[index];\n if (widget && !widget.isHidden) {\n this._toggleExpansion(index);\n }\n }\n /**\n * Expand the widget at position `index`.\n *\n * #### Notes\n * If no widget is found for `index`, this will bail.\n *\n * @param index Widget index\n */\n expand(index) {\n const widget = this.layout.widgets[index];\n if (widget && widget.isHidden) {\n this._toggleExpansion(index);\n }\n }\n /**\n * Insert a widget at the specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into to the panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n */\n insertWidget(index, widget) {\n super.insertWidget(index, widget);\n widget.title.changed.connect(this._onTitleChanged, this);\n }\n /**\n * Handle the DOM events for the accordion panel.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the panel's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n super.handleEvent(event);\n switch (event.type) {\n case 'click':\n this._evtClick(event);\n break;\n case 'keydown':\n this._eventKeyDown(event);\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('click', this);\n this.node.addEventListener('keydown', this);\n super.onBeforeAttach(msg);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n super.onAfterDetach(msg);\n this.node.removeEventListener('click', this);\n this.node.removeEventListener('keydown', this);\n }\n /**\n * Handle the `changed` signal of a title object.\n */\n _onTitleChanged(sender) {\n const index = ArrayExt.findFirstIndex(this.widgets, widget => {\n return widget.contains(sender.owner);\n });\n if (index >= 0) {\n this.layout.updateTitle(index, sender.owner);\n this.update();\n }\n }\n /**\n * Compute the size of widgets in this panel on the title click event.\n * On closing, the size of the widget is cached and we will try to expand\n * the last opened widget.\n * On opening, we will use the cached size if it is available to restore the\n * widget.\n * In both cases, if we can not compute the size of widgets, we will let\n * `SplitLayout` decide.\n *\n * @param index - The index of widget to be opened of closed\n *\n * @returns Relative size of widgets in this panel, if this size can\n * not be computed, return `undefined`\n */\n _computeWidgetSize(index) {\n const layout = this.layout;\n const widget = layout.widgets[index];\n if (!widget) {\n return undefined;\n }\n const isHidden = widget.isHidden;\n const widgetSizes = layout.absoluteSizes();\n const delta = (isHidden ? -1 : 1) * this.spacing;\n const totalSize = widgetSizes.reduce((prev, curr) => prev + curr);\n let newSize = [...widgetSizes];\n if (!isHidden) {\n // Hide the widget\n const currentSize = widgetSizes[index];\n this._widgetSizesCache.set(widget, currentSize);\n newSize[index] = 0;\n const widgetToCollapse = newSize.map(sz => sz > 0).lastIndexOf(true);\n if (widgetToCollapse === -1) {\n // All widget are closed, let the `SplitLayout` compute widget sizes.\n return undefined;\n }\n newSize[widgetToCollapse] =\n widgetSizes[widgetToCollapse] + currentSize + delta;\n }\n else {\n // Show the widget\n const previousSize = this._widgetSizesCache.get(widget);\n if (!previousSize) {\n // Previous size is unavailable, let the `SplitLayout` compute widget sizes.\n return undefined;\n }\n newSize[index] += previousSize;\n const widgetToCollapse = newSize\n .map(sz => sz - previousSize > 0)\n .lastIndexOf(true);\n if (widgetToCollapse === -1) {\n // Can not reduce the size of one widget, reduce all opened widgets\n // proportionally with its size.\n newSize.forEach((_, idx) => {\n if (idx !== index) {\n newSize[idx] -=\n (widgetSizes[idx] / totalSize) * (previousSize - delta);\n }\n });\n }\n else {\n newSize[widgetToCollapse] -= previousSize - delta;\n }\n }\n return newSize.map(sz => sz / (totalSize + delta));\n }\n /**\n * Handle the `'click'` event for the accordion panel\n */\n _evtClick(event) {\n const target = event.target;\n if (target) {\n const index = ArrayExt.findFirstIndex(this.titles, title => {\n return title.contains(target);\n });\n if (index >= 0) {\n event.preventDefault();\n event.stopPropagation();\n this._toggleExpansion(index);\n }\n }\n }\n /**\n * Handle the `'keydown'` event for the accordion panel.\n */\n _eventKeyDown(event) {\n if (event.defaultPrevented) {\n return;\n }\n const target = event.target;\n let handled = false;\n if (target) {\n const index = ArrayExt.findFirstIndex(this.titles, title => {\n return title.contains(target);\n });\n if (index >= 0) {\n const keyCode = event.keyCode.toString();\n // If Space or Enter is pressed on title, emulate click event\n if (event.key.match(/Space|Enter/) || keyCode.match(/13|32/)) {\n target.click();\n handled = true;\n }\n else if (this.orientation === 'horizontal'\n ? event.key.match(/ArrowLeft|ArrowRight/) || keyCode.match(/37|39/)\n : event.key.match(/ArrowUp|ArrowDown/) || keyCode.match(/38|40/)) {\n // If Up or Down (for vertical) / Left or Right (for horizontal) is pressed on title, loop on titles\n const direction = event.key.match(/ArrowLeft|ArrowUp/) || keyCode.match(/37|38/)\n ? -1\n : 1;\n const length = this.titles.length;\n const newIndex = (index + length + direction) % length;\n this.titles[newIndex].focus();\n handled = true;\n }\n else if (event.key === 'End' || keyCode === '35') {\n // If End is pressed on title, focus on the last title\n this.titles[this.titles.length - 1].focus();\n handled = true;\n }\n else if (event.key === 'Home' || keyCode === '36') {\n // If Home is pressed on title, focus on the first title\n this.titles[0].focus();\n handled = true;\n }\n }\n if (handled) {\n event.preventDefault();\n }\n }\n }\n _toggleExpansion(index) {\n const title = this.titles[index];\n const widget = this.layout.widgets[index];\n const newSize = this._computeWidgetSize(index);\n if (newSize) {\n this.setRelativeSizes(newSize, false);\n }\n if (widget.isHidden) {\n title.classList.add('lm-mod-expanded');\n title.setAttribute('aria-expanded', 'true');\n widget.show();\n }\n else {\n title.classList.remove('lm-mod-expanded');\n title.setAttribute('aria-expanded', 'false');\n widget.hide();\n }\n // Emit the expansion state signal.\n this._expansionToggled.emit(index);\n }\n}\n/**\n * The namespace for the `AccordionPanel` class statics.\n */\n(function (AccordionPanel) {\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer extends SplitPanel.Renderer {\n constructor() {\n super();\n /**\n * A selector which matches any title node in the accordion.\n */\n this.titleClassName = 'lm-AccordionPanel-title';\n this._titleID = 0;\n this._titleKeys = new WeakMap();\n this._uuid = ++Renderer._nInstance;\n }\n /**\n * Render the collapse indicator for a section title.\n *\n * @param data - The data to use for rendering the section title.\n *\n * @returns A element representing the collapse indicator.\n */\n createCollapseIcon(data) {\n return document.createElement('span');\n }\n /**\n * Render the element for a section title.\n *\n * @param data - The data to use for rendering the section title.\n *\n * @returns A element representing the section title.\n */\n createSectionTitle(data) {\n const handle = document.createElement('h3');\n handle.setAttribute('tabindex', '0');\n handle.id = this.createTitleKey(data);\n handle.className = this.titleClassName;\n for (const aData in data.dataset) {\n handle.dataset[aData] = data.dataset[aData];\n }\n const collapser = handle.appendChild(this.createCollapseIcon(data));\n collapser.className = 'lm-AccordionPanel-titleCollapser';\n const label = handle.appendChild(document.createElement('span'));\n label.className = 'lm-AccordionPanel-titleLabel';\n label.textContent = data.label;\n label.title = data.caption || data.label;\n return handle;\n }\n /**\n * Create a unique render key for the title.\n *\n * @param data - The data to use for the title.\n *\n * @returns The unique render key for the title.\n *\n * #### Notes\n * This method caches the key against the section title the first time\n * the key is generated.\n */\n createTitleKey(data) {\n let key = this._titleKeys.get(data);\n if (key === undefined) {\n key = `title-key-${this._uuid}-${this._titleID++}`;\n this._titleKeys.set(data, key);\n }\n return key;\n }\n }\n Renderer._nInstance = 0;\n AccordionPanel.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n AccordionPanel.defaultRenderer = new Renderer();\n})(AccordionPanel || (AccordionPanel = {}));\nvar Private$d;\n(function (Private) {\n /**\n * Create an accordion layout for the given panel options.\n *\n * @param options Panel options\n * @returns Panel layout\n */\n function createLayout(options) {\n return (options.layout ||\n new AccordionLayout({\n renderer: options.renderer || AccordionPanel.defaultRenderer,\n orientation: options.orientation,\n alignment: options.alignment,\n spacing: options.spacing,\n titleSpace: options.titleSpace\n }));\n }\n Private.createLayout = createLayout;\n})(Private$d || (Private$d = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which arranges its widgets in a single row or column.\n */\nclass BoxLayout extends PanelLayout {\n /**\n * Construct a new box layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options = {}) {\n super();\n this._fixed = 0;\n this._spacing = 4;\n this._dirty = false;\n this._sizers = [];\n this._items = [];\n this._box = null;\n this._alignment = 'start';\n this._direction = 'top-to-bottom';\n if (options.direction !== undefined) {\n this._direction = options.direction;\n }\n if (options.alignment !== undefined) {\n this._alignment = options.alignment;\n }\n if (options.spacing !== undefined) {\n this._spacing = Utils$1.clampDimension(options.spacing);\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the layout items.\n for (const item of this._items) {\n item.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n this._sizers.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Get the layout direction for the box layout.\n */\n get direction() {\n return this._direction;\n }\n /**\n * Set the layout direction for the box layout.\n */\n set direction(value) {\n if (this._direction === value) {\n return;\n }\n this._direction = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['direction'] = value;\n this.parent.fit();\n }\n /**\n * Get the content alignment for the box layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n get alignment() {\n return this._alignment;\n }\n /**\n * Set the content alignment for the box layout.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n set alignment(value) {\n if (this._alignment === value) {\n return;\n }\n this._alignment = value;\n if (!this.parent) {\n return;\n }\n this.parent.dataset['alignment'] = value;\n this.parent.update();\n }\n /**\n * Get the inter-element spacing for the box layout.\n */\n get spacing() {\n return this._spacing;\n }\n /**\n * Set the inter-element spacing for the box layout.\n */\n set spacing(value) {\n value = Utils$1.clampDimension(value);\n if (this._spacing === value) {\n return;\n }\n this._spacing = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n this.parent.dataset['direction'] = this.direction;\n this.parent.dataset['alignment'] = this.alignment;\n super.init();\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n attachWidget(index, widget) {\n // Create and add a new layout item for the widget.\n ArrayExt.insert(this._items, index, new LayoutItem(widget));\n // Create and add a new sizer for the widget.\n ArrayExt.insert(this._sizers, index, new BoxSizer());\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Move the layout item for the widget.\n ArrayExt.move(this._items, fromIndex, toIndex);\n // Move the sizer for the widget.\n ArrayExt.move(this._sizers, fromIndex, toIndex);\n // Post an update request for the parent widget.\n this.parent.update();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n // Remove the layout item for the widget.\n let item = ArrayExt.removeAt(this._items, index);\n // Remove the sizer for the widget.\n ArrayExt.removeAt(this._sizers, index);\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Dispose of the layout item.\n item.dispose();\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Update the fixed space for the visible items.\n this._fixed = this._spacing * Math.max(0, nVisible - 1);\n // Setup the computed minimum size.\n let horz = Private$c.isHorizontal(this._direction);\n let minW = horz ? this._fixed : 0;\n let minH = horz ? 0 : this._fixed;\n // Update the sizers and computed minimum size.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item and corresponding box sizer.\n let item = this._items[i];\n let sizer = this._sizers[i];\n // If the item is hidden, it should consume zero size.\n if (item.isHidden) {\n sizer.minSize = 0;\n sizer.maxSize = 0;\n continue;\n }\n // Update the size limits for the item.\n item.fit();\n // Update the size basis and stretch factor.\n sizer.sizeHint = BoxLayout.getSizeBasis(item.widget);\n sizer.stretch = BoxLayout.getStretch(item.widget);\n // Update the sizer limits and computed min size.\n if (horz) {\n sizer.minSize = item.minWidth;\n sizer.maxSize = item.maxWidth;\n minW += item.minWidth;\n minH = Math.max(minH, item.minHeight);\n }\n else {\n sizer.minSize = item.minHeight;\n sizer.maxSize = item.maxHeight;\n minH += item.minHeight;\n minW = Math.max(minW, item.minWidth);\n }\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Bail early if there are no visible items to layout.\n if (nVisible === 0) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the layout area adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Distribute the layout space and adjust the start position.\n let delta;\n switch (this._direction) {\n case 'left-to-right':\n delta = BoxEngine.calc(this._sizers, Math.max(0, width - this._fixed));\n break;\n case 'top-to-bottom':\n delta = BoxEngine.calc(this._sizers, Math.max(0, height - this._fixed));\n break;\n case 'right-to-left':\n delta = BoxEngine.calc(this._sizers, Math.max(0, width - this._fixed));\n left += width;\n break;\n case 'bottom-to-top':\n delta = BoxEngine.calc(this._sizers, Math.max(0, height - this._fixed));\n top += height;\n break;\n default:\n throw 'unreachable';\n }\n // Setup the variables for justification and alignment offset.\n let extra = 0;\n let offset = 0;\n // Account for alignment if there is extra layout space.\n if (delta > 0) {\n switch (this._alignment) {\n case 'start':\n break;\n case 'center':\n extra = 0;\n offset = delta / 2;\n break;\n case 'end':\n extra = 0;\n offset = delta;\n break;\n case 'justify':\n extra = delta / nVisible;\n offset = 0;\n break;\n default:\n throw 'unreachable';\n }\n }\n // Layout the items using the computed box sizes.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Fetch the computed size for the widget.\n let size = this._sizers[i].size;\n // Update the widget geometry and advance the relevant edge.\n switch (this._direction) {\n case 'left-to-right':\n item.update(left + offset, top, size + extra, height);\n left += size + extra + this._spacing;\n break;\n case 'top-to-bottom':\n item.update(left, top + offset, width, size + extra);\n top += size + extra + this._spacing;\n break;\n case 'right-to-left':\n item.update(left - offset - size - extra, top, size + extra, height);\n left -= size + extra + this._spacing;\n break;\n case 'bottom-to-top':\n item.update(left, top - offset - size - extra, width, size + extra);\n top -= size + extra + this._spacing;\n break;\n default:\n throw 'unreachable';\n }\n }\n }\n}\n/**\n * The namespace for the `BoxLayout` class statics.\n */\n(function (BoxLayout) {\n /**\n * Get the box layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box layout stretch factor for the widget.\n */\n function getStretch(widget) {\n return Private$c.stretchProperty.get(widget);\n }\n BoxLayout.getStretch = getStretch;\n /**\n * Set the box layout stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n Private$c.stretchProperty.set(widget, value);\n }\n BoxLayout.setStretch = setStretch;\n /**\n * Get the box layout size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box layout size basis for the widget.\n */\n function getSizeBasis(widget) {\n return Private$c.sizeBasisProperty.get(widget);\n }\n BoxLayout.getSizeBasis = getSizeBasis;\n /**\n * Set the box layout size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the size basis.\n */\n function setSizeBasis(widget, value) {\n Private$c.sizeBasisProperty.set(widget, value);\n }\n BoxLayout.setSizeBasis = setSizeBasis;\n})(BoxLayout || (BoxLayout = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$c;\n(function (Private) {\n /**\n * The property descriptor for a widget stretch factor.\n */\n Private.stretchProperty = new AttachedProperty({\n name: 'stretch',\n create: () => 0,\n coerce: (owner, value) => Math.max(0, Math.floor(value)),\n changed: onChildSizingChanged\n });\n /**\n * The property descriptor for a widget size basis.\n */\n Private.sizeBasisProperty = new AttachedProperty({\n name: 'sizeBasis',\n create: () => 0,\n coerce: (owner, value) => Math.max(0, Math.floor(value)),\n changed: onChildSizingChanged\n });\n /**\n * Test whether a direction has horizontal orientation.\n */\n function isHorizontal(dir) {\n return dir === 'left-to-right' || dir === 'right-to-left';\n }\n Private.isHorizontal = isHorizontal;\n /**\n * Clamp a spacing value to an integer >= 0.\n */\n function clampSpacing(value) {\n return Math.max(0, Math.floor(value));\n }\n Private.clampSpacing = clampSpacing;\n /**\n * The change handler for the attached sizing properties.\n */\n function onChildSizingChanged(child) {\n if (child.parent && child.parent.layout instanceof BoxLayout) {\n child.parent.fit();\n }\n }\n})(Private$c || (Private$c = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A panel which arranges its widgets in a single row or column.\n *\n * #### Notes\n * This class provides a convenience wrapper around a {@link BoxLayout}.\n */\nclass BoxPanel extends Panel {\n /**\n * Construct a new box panel.\n *\n * @param options - The options for initializing the box panel.\n */\n constructor(options = {}) {\n super({ layout: Private$b.createLayout(options) });\n this.addClass('lm-BoxPanel');\n }\n /**\n * Get the layout direction for the box panel.\n */\n get direction() {\n return this.layout.direction;\n }\n /**\n * Set the layout direction for the box panel.\n */\n set direction(value) {\n this.layout.direction = value;\n }\n /**\n * Get the content alignment for the box panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n get alignment() {\n return this.layout.alignment;\n }\n /**\n * Set the content alignment for the box panel.\n *\n * #### Notes\n * This is the alignment of the widgets in the layout direction.\n *\n * The alignment has no effect if the widgets can expand to fill the\n * entire box layout.\n */\n set alignment(value) {\n this.layout.alignment = value;\n }\n /**\n * Get the inter-element spacing for the box panel.\n */\n get spacing() {\n return this.layout.spacing;\n }\n /**\n * Set the inter-element spacing for the box panel.\n */\n set spacing(value) {\n this.layout.spacing = value;\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n msg.child.addClass('lm-BoxPanel-child');\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n msg.child.removeClass('lm-BoxPanel-child');\n }\n}\n/**\n * The namespace for the `BoxPanel` class statics.\n */\n(function (BoxPanel) {\n /**\n * Get the box panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box panel stretch factor for the widget.\n */\n function getStretch(widget) {\n return BoxLayout.getStretch(widget);\n }\n BoxPanel.getStretch = getStretch;\n /**\n * Set the box panel stretch factor for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the stretch factor.\n */\n function setStretch(widget, value) {\n BoxLayout.setStretch(widget, value);\n }\n BoxPanel.setStretch = setStretch;\n /**\n * Get the box panel size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The box panel size basis for the widget.\n */\n function getSizeBasis(widget) {\n return BoxLayout.getSizeBasis(widget);\n }\n BoxPanel.getSizeBasis = getSizeBasis;\n /**\n * Set the box panel size basis for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the size basis.\n */\n function setSizeBasis(widget, value) {\n BoxLayout.setSizeBasis(widget, value);\n }\n BoxPanel.setSizeBasis = setSizeBasis;\n})(BoxPanel || (BoxPanel = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$b;\n(function (Private) {\n /**\n * Create a box layout for the given panel options.\n */\n function createLayout(options) {\n return options.layout || new BoxLayout(options);\n }\n Private.createLayout = createLayout;\n})(Private$b || (Private$b = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which displays command items as a searchable palette.\n */\nclass CommandPalette extends Widget {\n /**\n * Construct a new command palette.\n *\n * @param options - The options for initializing the palette.\n */\n constructor(options) {\n super({ node: Private$a.createNode() });\n this._activeIndex = -1;\n this._items = [];\n this._results = null;\n this.addClass('lm-CommandPalette');\n this.setFlag(Widget.Flag.DisallowLayout);\n this.commands = options.commands;\n this.renderer = options.renderer || CommandPalette.defaultRenderer;\n this.commands.commandChanged.connect(this._onGenericChange, this);\n this.commands.keyBindingChanged.connect(this._onGenericChange, this);\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n this._items.length = 0;\n this._results = null;\n super.dispose();\n }\n /**\n * The command palette search node.\n *\n * #### Notes\n * This is the node which contains the search-related elements.\n */\n get searchNode() {\n return this.node.getElementsByClassName('lm-CommandPalette-search')[0];\n }\n /**\n * The command palette input node.\n *\n * #### Notes\n * This is the actual input node for the search area.\n */\n get inputNode() {\n return this.node.getElementsByClassName('lm-CommandPalette-input')[0];\n }\n /**\n * The command palette content node.\n *\n * #### Notes\n * This is the node which holds the command item nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-CommandPalette-content')[0];\n }\n /**\n * A read-only array of the command items in the palette.\n */\n get items() {\n return this._items;\n }\n /**\n * Add a command item to the command palette.\n *\n * @param options - The options for creating the command item.\n *\n * @returns The command item added to the palette.\n */\n addItem(options) {\n // Create a new command item for the options.\n let item = Private$a.createItem(this.commands, options);\n // Add the item to the array.\n this._items.push(item);\n // Refresh the search results.\n this.refresh();\n // Return the item added to the palette.\n return item;\n }\n /**\n * Adds command items to the command palette.\n *\n * @param items - An array of options for creating each command item.\n *\n * @returns The command items added to the palette.\n */\n addItems(items) {\n const newItems = items.map(item => Private$a.createItem(this.commands, item));\n newItems.forEach(item => this._items.push(item));\n this.refresh();\n return newItems;\n }\n /**\n * Remove an item from the command palette.\n *\n * @param item - The item to remove from the palette.\n *\n * #### Notes\n * This is a no-op if the item is not in the palette.\n */\n removeItem(item) {\n this.removeItemAt(this._items.indexOf(item));\n }\n /**\n * Remove the item at a given index from the command palette.\n *\n * @param index - The index of the item to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeItemAt(index) {\n // Remove the item from the array.\n let item = ArrayExt.removeAt(this._items, index);\n // Bail if the index is out of range.\n if (!item) {\n return;\n }\n // Refresh the search results.\n this.refresh();\n }\n /**\n * Remove all items from the command palette.\n */\n clearItems() {\n // Bail if there is nothing to remove.\n if (this._items.length === 0) {\n return;\n }\n // Clear the array of items.\n this._items.length = 0;\n // Refresh the search results.\n this.refresh();\n }\n /**\n * Clear the search results and schedule an update.\n *\n * #### Notes\n * This should be called whenever the search results of the palette\n * should be updated.\n *\n * This is typically called automatically by the palette as needed,\n * but can be called manually if the input text is programatically\n * changed.\n *\n * The rendered results are updated asynchronously.\n */\n refresh() {\n this._results = null;\n if (this.inputNode.value !== '') {\n let clear = this.node.getElementsByClassName('lm-close-icon')[0];\n clear.style.display = 'inherit';\n }\n else {\n let clear = this.node.getElementsByClassName('lm-close-icon')[0];\n clear.style.display = 'none';\n }\n this.update();\n }\n /**\n * Handle the DOM events for the command palette.\n *\n * @param event - The DOM event sent to the command palette.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the command palette's DOM node.\n * It should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'click':\n this._evtClick(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'input':\n this.refresh();\n break;\n case 'focus':\n case 'blur':\n this._toggleFocused();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('click', this);\n this.node.addEventListener('keydown', this);\n this.node.addEventListener('input', this);\n this.node.addEventListener('focus', this, true);\n this.node.addEventListener('blur', this, true);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('click', this);\n this.node.removeEventListener('keydown', this);\n this.node.removeEventListener('input', this);\n this.node.removeEventListener('focus', this, true);\n this.node.removeEventListener('blur', this, true);\n }\n /**\n * A message handler invoked on an `'after-show'` message.\n */\n onAfterShow(msg) {\n this.update();\n super.onAfterShow(msg);\n }\n /**\n * A message handler invoked on an `'activate-request'` message.\n */\n onActivateRequest(msg) {\n if (this.isAttached) {\n let input = this.inputNode;\n input.focus();\n input.select();\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.isHidden) {\n return;\n }\n // Fetch the current query text and content node.\n let query = this.inputNode.value;\n let contentNode = this.contentNode;\n // Ensure the search results are generated.\n let results = this._results;\n if (!results) {\n // Generate and store the new search results.\n results = this._results = Private$a.search(this._items, query);\n // Reset the active index.\n this._activeIndex = query\n ? ArrayExt.findFirstIndex(results, Private$a.canActivate)\n : -1;\n }\n // If there is no query and no results, clear the content.\n if (!query && results.length === 0) {\n VirtualDOM.render(null, contentNode);\n return;\n }\n // If the is a query but no results, render the empty message.\n if (query && results.length === 0) {\n let content = this.renderer.renderEmptyMessage({ query });\n VirtualDOM.render(content, contentNode);\n return;\n }\n // Create the render content for the search results.\n let renderer = this.renderer;\n let activeIndex = this._activeIndex;\n let content = new Array(results.length);\n for (let i = 0, n = results.length; i < n; ++i) {\n let result = results[i];\n if (result.type === 'header') {\n let indices = result.indices;\n let category = result.category;\n content[i] = renderer.renderHeader({ category, indices });\n }\n else {\n let item = result.item;\n let indices = result.indices;\n let active = i === activeIndex;\n content[i] = renderer.renderItem({ item, indices, active });\n }\n }\n // Render the search result content.\n VirtualDOM.render(content, contentNode);\n // Adjust the scroll position as needed.\n if (activeIndex < 0 || activeIndex >= results.length) {\n contentNode.scrollTop = 0;\n }\n else {\n let element = contentNode.children[activeIndex];\n ElementExt.scrollIntoViewIfNeeded(contentNode, element);\n }\n }\n /**\n * Handle the `'click'` event for the command palette.\n */\n _evtClick(event) {\n // Bail if the click is not the left button.\n if (event.button !== 0) {\n return;\n }\n // Clear input if the target is clear button\n if (event.target.classList.contains('lm-close-icon')) {\n this.inputNode.value = '';\n this.refresh();\n return;\n }\n // Find the index of the item which was clicked.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return node.contains(event.target);\n });\n // Bail if the click was not on an item.\n if (index === -1) {\n return;\n }\n // Kill the event when a content item is clicked.\n event.preventDefault();\n event.stopPropagation();\n // Execute the item if possible.\n this._execute(index);\n }\n /**\n * Handle the `'keydown'` event for the command palette.\n */\n _evtKeyDown(event) {\n if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n switch (event.keyCode) {\n case 13: // Enter\n event.preventDefault();\n event.stopPropagation();\n this._execute(this._activeIndex);\n break;\n case 38: // Up Arrow\n event.preventDefault();\n event.stopPropagation();\n this._activatePreviousItem();\n break;\n case 40: // Down Arrow\n event.preventDefault();\n event.stopPropagation();\n this._activateNextItem();\n break;\n }\n }\n /**\n * Activate the next enabled command item.\n */\n _activateNextItem() {\n // Bail if there are no search results.\n if (!this._results || this._results.length === 0) {\n return;\n }\n // Find the next enabled item index.\n let ai = this._activeIndex;\n let n = this._results.length;\n let start = ai < n - 1 ? ai + 1 : 0;\n let stop = start === 0 ? n - 1 : start - 1;\n this._activeIndex = ArrayExt.findFirstIndex(this._results, Private$a.canActivate, start, stop);\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Activate the previous enabled command item.\n */\n _activatePreviousItem() {\n // Bail if there are no search results.\n if (!this._results || this._results.length === 0) {\n return;\n }\n // Find the previous enabled item index.\n let ai = this._activeIndex;\n let n = this._results.length;\n let start = ai <= 0 ? n - 1 : ai - 1;\n let stop = start === n - 1 ? 0 : start + 1;\n this._activeIndex = ArrayExt.findLastIndex(this._results, Private$a.canActivate, start, stop);\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Execute the command item at the given index, if possible.\n */\n _execute(index) {\n // Bail if there are no search results.\n if (!this._results) {\n return;\n }\n // Bail if the index is out of range.\n let part = this._results[index];\n if (!part) {\n return;\n }\n // Update the search text if the item is a header.\n if (part.type === 'header') {\n let input = this.inputNode;\n input.value = `${part.category.toLowerCase()} `;\n input.focus();\n this.refresh();\n return;\n }\n // Bail if item is not enabled.\n if (!part.item.isEnabled) {\n return;\n }\n // Execute the item.\n this.commands.execute(part.item.command, part.item.args);\n // Clear the query text.\n this.inputNode.value = '';\n // Refresh the search results.\n this.refresh();\n }\n /**\n * Toggle the focused modifier based on the input node focus state.\n */\n _toggleFocused() {\n let focused = document.activeElement === this.inputNode;\n this.toggleClass('lm-mod-focused', focused);\n }\n /**\n * A signal handler for generic command changes.\n */\n _onGenericChange() {\n this.refresh();\n }\n}\n/**\n * The namespace for the `CommandPalette` class statics.\n */\n(function (CommandPalette) {\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer {\n /**\n * Render the virtual element for a command palette header.\n *\n * @param data - The data to use for rendering the header.\n *\n * @returns A virtual element representing the header.\n */\n renderHeader(data) {\n let content = this.formatHeader(data);\n return h.li({ className: 'lm-CommandPalette-header' }, content);\n }\n /**\n * Render the virtual element for a command palette item.\n *\n * @param data - The data to use for rendering the item.\n *\n * @returns A virtual element representing the item.\n */\n renderItem(data) {\n let className = this.createItemClass(data);\n let dataset = this.createItemDataset(data);\n if (data.item.isToggleable) {\n return h.li({\n className,\n dataset,\n role: 'menuitemcheckbox',\n 'aria-checked': `${data.item.isToggled}`\n }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data));\n }\n return h.li({\n className,\n dataset,\n role: 'menuitem'\n }, this.renderItemIcon(data), this.renderItemContent(data), this.renderItemShortcut(data));\n }\n /**\n * Render the empty results message for a command palette.\n *\n * @param data - The data to use for rendering the message.\n *\n * @returns A virtual element representing the message.\n */\n renderEmptyMessage(data) {\n let content = this.formatEmptyMessage(data);\n return h.li({ className: 'lm-CommandPalette-emptyMessage' }, content);\n }\n /**\n * Render the icon for a command palette item.\n *\n * @param data - The data to use for rendering the icon.\n *\n * @returns A virtual element representing the icon.\n */\n renderItemIcon(data) {\n let className = this.createIconClass(data);\n // If data.item.icon is undefined, it will be ignored.\n return h.div({ className }, data.item.icon, data.item.iconLabel);\n }\n /**\n * Render the content for a command palette item.\n *\n * @param data - The data to use for rendering the content.\n *\n * @returns A virtual element representing the content.\n */\n renderItemContent(data) {\n return h.div({ className: 'lm-CommandPalette-itemContent' }, this.renderItemLabel(data), this.renderItemCaption(data));\n }\n /**\n * Render the label for a command palette item.\n *\n * @param data - The data to use for rendering the label.\n *\n * @returns A virtual element representing the label.\n */\n renderItemLabel(data) {\n let content = this.formatItemLabel(data);\n return h.div({ className: 'lm-CommandPalette-itemLabel' }, content);\n }\n /**\n * Render the caption for a command palette item.\n *\n * @param data - The data to use for rendering the caption.\n *\n * @returns A virtual element representing the caption.\n */\n renderItemCaption(data) {\n let content = this.formatItemCaption(data);\n return h.div({ className: 'lm-CommandPalette-itemCaption' }, content);\n }\n /**\n * Render the shortcut for a command palette item.\n *\n * @param data - The data to use for rendering the shortcut.\n *\n * @returns A virtual element representing the shortcut.\n */\n renderItemShortcut(data) {\n let content = this.formatItemShortcut(data);\n return h.div({ className: 'lm-CommandPalette-itemShortcut' }, content);\n }\n /**\n * Create the class name for the command palette item.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the command palette item.\n */\n createItemClass(data) {\n // Set up the initial class name.\n let name = 'lm-CommandPalette-item';\n // Add the boolean state classes.\n if (!data.item.isEnabled) {\n name += ' lm-mod-disabled';\n }\n if (data.item.isToggled) {\n name += ' lm-mod-toggled';\n }\n if (data.active) {\n name += ' lm-mod-active';\n }\n // Add the extra class.\n let extra = data.item.className;\n if (extra) {\n name += ` ${extra}`;\n }\n // Return the complete class name.\n return name;\n }\n /**\n * Create the dataset for the command palette item.\n *\n * @param data - The data to use for creating the dataset.\n *\n * @returns The dataset for the command palette item.\n */\n createItemDataset(data) {\n return { ...data.item.dataset, command: data.item.command };\n }\n /**\n * Create the class name for the command item icon.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the item icon.\n */\n createIconClass(data) {\n let name = 'lm-CommandPalette-itemIcon';\n let extra = data.item.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n /**\n * Create the render content for the header node.\n *\n * @param data - The data to use for the header content.\n *\n * @returns The content to add to the header node.\n */\n formatHeader(data) {\n if (!data.indices || data.indices.length === 0) {\n return data.category;\n }\n return StringExt.highlight(data.category, data.indices, h.mark);\n }\n /**\n * Create the render content for the empty message node.\n *\n * @param data - The data to use for the empty message content.\n *\n * @returns The content to add to the empty message node.\n */\n formatEmptyMessage(data) {\n return `No commands found that match '${data.query}'`;\n }\n /**\n * Create the render content for the item shortcut node.\n *\n * @param data - The data to use for the shortcut content.\n *\n * @returns The content to add to the shortcut node.\n */\n formatItemShortcut(data) {\n let kb = data.item.keyBinding;\n return kb ? CommandRegistry.formatKeystroke(kb.keys) : null;\n }\n /**\n * Create the render content for the item label node.\n *\n * @param data - The data to use for the label content.\n *\n * @returns The content to add to the label node.\n */\n formatItemLabel(data) {\n if (!data.indices || data.indices.length === 0) {\n return data.item.label;\n }\n return StringExt.highlight(data.item.label, data.indices, h.mark);\n }\n /**\n * Create the render content for the item caption node.\n *\n * @param data - The data to use for the caption content.\n *\n * @returns The content to add to the caption node.\n */\n formatItemCaption(data) {\n return data.item.caption;\n }\n }\n CommandPalette.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n CommandPalette.defaultRenderer = new Renderer();\n})(CommandPalette || (CommandPalette = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$a;\n(function (Private) {\n /**\n * Create the DOM node for a command palette.\n */\n function createNode() {\n let node = document.createElement('div');\n let search = document.createElement('div');\n let wrapper = document.createElement('div');\n let input = document.createElement('input');\n let content = document.createElement('ul');\n let clear = document.createElement('button');\n search.className = 'lm-CommandPalette-search';\n wrapper.className = 'lm-CommandPalette-wrapper';\n input.className = 'lm-CommandPalette-input';\n clear.className = 'lm-close-icon';\n content.className = 'lm-CommandPalette-content';\n content.setAttribute('role', 'menu');\n input.spellcheck = false;\n wrapper.appendChild(input);\n wrapper.appendChild(clear);\n search.appendChild(wrapper);\n node.appendChild(search);\n node.appendChild(content);\n return node;\n }\n Private.createNode = createNode;\n /**\n * Create a new command item from a command registry and options.\n */\n function createItem(commands, options) {\n return new CommandItem(commands, options);\n }\n Private.createItem = createItem;\n /**\n * Search an array of command items for fuzzy matches.\n */\n function search(items, query) {\n // Fuzzy match the items for the query.\n let scores = matchItems(items, query);\n // Sort the items based on their score.\n scores.sort(scoreCmp);\n // Create the results for the search.\n return createResults(scores);\n }\n Private.search = search;\n /**\n * Test whether a result item can be activated.\n */\n function canActivate(result) {\n return result.type === 'item' && result.item.isEnabled;\n }\n Private.canActivate = canActivate;\n /**\n * Normalize a category for a command item.\n */\n function normalizeCategory(category) {\n return category.trim().replace(/\\s+/g, ' ');\n }\n /**\n * Normalize the query text for a fuzzy search.\n */\n function normalizeQuery(text) {\n return text.replace(/\\s+/g, '').toLowerCase();\n }\n /**\n * Perform a fuzzy match on an array of command items.\n */\n function matchItems(items, query) {\n // Normalize the query text to lower case with no whitespace.\n query = normalizeQuery(query);\n // Create the array to hold the scores.\n let scores = [];\n // Iterate over the items and match against the query.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Ignore items which are not visible.\n let item = items[i];\n if (!item.isVisible) {\n continue;\n }\n // If the query is empty, all items are matched by default.\n if (!query) {\n scores.push({\n matchType: 3 /* MatchType.Default */,\n categoryIndices: null,\n labelIndices: null,\n score: 0,\n item\n });\n continue;\n }\n // Run the fuzzy search for the item and query.\n let score = fuzzySearch(item, query);\n // Ignore the item if it is not a match.\n if (!score) {\n continue;\n }\n // Penalize disabled items.\n // TODO - push disabled items all the way down in sort cmp?\n if (!item.isEnabled) {\n score.score += 1000;\n }\n // Add the score to the results.\n scores.push(score);\n }\n // Return the final array of scores.\n return scores;\n }\n /**\n * Perform a fuzzy search on a single command item.\n */\n function fuzzySearch(item, query) {\n // Create the source text to be searched.\n let category = item.category.toLowerCase();\n let label = item.label.toLowerCase();\n let source = `${category} ${label}`;\n // Set up the match score and indices array.\n let score = Infinity;\n let indices = null;\n // The regex for search word boundaries\n let rgx = /\\b\\w/g;\n // Search the source by word boundary.\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // Find the next word boundary in the source.\n let rgxMatch = rgx.exec(source);\n // Break if there is no more source context.\n if (!rgxMatch) {\n break;\n }\n // Run the string match on the relevant substring.\n let match = StringExt.matchSumOfDeltas(source, query, rgxMatch.index);\n // Break if there is no match.\n if (!match) {\n break;\n }\n // Update the match if the score is better.\n if (match.score <= score) {\n score = match.score;\n indices = match.indices;\n }\n }\n // Bail if there was no match.\n if (!indices || score === Infinity) {\n return null;\n }\n // Compute the pivot index between category and label text.\n let pivot = category.length + 1;\n // Find the slice index to separate matched indices.\n let j = ArrayExt.lowerBound(indices, pivot, (a, b) => a - b);\n // Extract the matched category and label indices.\n let categoryIndices = indices.slice(0, j);\n let labelIndices = indices.slice(j);\n // Adjust the label indices for the pivot offset.\n for (let i = 0, n = labelIndices.length; i < n; ++i) {\n labelIndices[i] -= pivot;\n }\n // Handle a pure label match.\n if (categoryIndices.length === 0) {\n return {\n matchType: 0 /* MatchType.Label */,\n categoryIndices: null,\n labelIndices,\n score,\n item\n };\n }\n // Handle a pure category match.\n if (labelIndices.length === 0) {\n return {\n matchType: 1 /* MatchType.Category */,\n categoryIndices,\n labelIndices: null,\n score,\n item\n };\n }\n // Handle a split match.\n return {\n matchType: 2 /* MatchType.Split */,\n categoryIndices,\n labelIndices,\n score,\n item\n };\n }\n /**\n * A sort comparison function for a match score.\n */\n function scoreCmp(a, b) {\n // First compare based on the match type\n let m1 = a.matchType - b.matchType;\n if (m1 !== 0) {\n return m1;\n }\n // Otherwise, compare based on the match score.\n let d1 = a.score - b.score;\n if (d1 !== 0) {\n return d1;\n }\n // Find the match index based on the match type.\n let i1 = 0;\n let i2 = 0;\n switch (a.matchType) {\n case 0 /* MatchType.Label */:\n i1 = a.labelIndices[0];\n i2 = b.labelIndices[0];\n break;\n case 1 /* MatchType.Category */:\n case 2 /* MatchType.Split */:\n i1 = a.categoryIndices[0];\n i2 = b.categoryIndices[0];\n break;\n }\n // Compare based on the match index.\n if (i1 !== i2) {\n return i1 - i2;\n }\n // Otherwise, compare by category.\n let d2 = a.item.category.localeCompare(b.item.category);\n if (d2 !== 0) {\n return d2;\n }\n // Otherwise, compare by rank.\n let r1 = a.item.rank;\n let r2 = b.item.rank;\n if (r1 !== r2) {\n return r1 < r2 ? -1 : 1; // Infinity safe\n }\n // Finally, compare by label.\n return a.item.label.localeCompare(b.item.label);\n }\n /**\n * Create the results from an array of sorted scores.\n */\n function createResults(scores) {\n // Set up an array to track which scores have been visited.\n let visited = new Array(scores.length);\n ArrayExt.fill(visited, false);\n // Set up the search results array.\n let results = [];\n // Iterate over each score in the array.\n for (let i = 0, n = scores.length; i < n; ++i) {\n // Ignore a score which has already been processed.\n if (visited[i]) {\n continue;\n }\n // Extract the current item and indices.\n let { item, categoryIndices } = scores[i];\n // Extract the category for the current item.\n let category = item.category;\n // Add the header result for the category.\n results.push({ type: 'header', category, indices: categoryIndices });\n // Find the rest of the scores with the same category.\n for (let j = i; j < n; ++j) {\n // Ignore a score which has already been processed.\n if (visited[j]) {\n continue;\n }\n // Extract the data for the current score.\n let { item, labelIndices } = scores[j];\n // Ignore an item with a different category.\n if (item.category !== category) {\n continue;\n }\n // Create the item result for the score.\n results.push({ type: 'item', item, indices: labelIndices });\n // Mark the score as processed.\n visited[j] = true;\n }\n }\n // Return the final results.\n return results;\n }\n /**\n * A concrete implementation of `CommandPalette.IItem`.\n */\n class CommandItem {\n /**\n * Construct a new command item.\n */\n constructor(commands, options) {\n this._commands = commands;\n this.category = normalizeCategory(options.category);\n this.command = options.command;\n this.args = options.args || JSONExt.emptyObject;\n this.rank = options.rank !== undefined ? options.rank : Infinity;\n }\n /**\n * The display label for the command item.\n */\n get label() {\n return this._commands.label(this.command, this.args);\n }\n /**\n * The icon renderer for the command item.\n */\n get icon() {\n return this._commands.icon(this.command, this.args);\n }\n /**\n * The icon class for the command item.\n */\n get iconClass() {\n return this._commands.iconClass(this.command, this.args);\n }\n /**\n * The icon label for the command item.\n */\n get iconLabel() {\n return this._commands.iconLabel(this.command, this.args);\n }\n /**\n * The display caption for the command item.\n */\n get caption() {\n return this._commands.caption(this.command, this.args);\n }\n /**\n * The extra class name for the command item.\n */\n get className() {\n return this._commands.className(this.command, this.args);\n }\n /**\n * The dataset for the command item.\n */\n get dataset() {\n return this._commands.dataset(this.command, this.args);\n }\n /**\n * Whether the command item is enabled.\n */\n get isEnabled() {\n return this._commands.isEnabled(this.command, this.args);\n }\n /**\n * Whether the command item is toggled.\n */\n get isToggled() {\n return this._commands.isToggled(this.command, this.args);\n }\n /**\n * Whether the command item is toggleable.\n */\n get isToggleable() {\n return this._commands.isToggleable(this.command, this.args);\n }\n /**\n * Whether the command item is visible.\n */\n get isVisible() {\n return this._commands.isVisible(this.command, this.args);\n }\n /**\n * The key binding for the command item.\n */\n get keyBinding() {\n let { command, args } = this;\n return (ArrayExt.findLastValue(this._commands.keyBindings, kb => {\n return kb.command === command && JSONExt.deepEqual(kb.args, args);\n }) || null);\n }\n }\n})(Private$a || (Private$a = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which displays items as a canonical menu.\n */\nclass Menu extends Widget {\n /**\n * Construct a new menu.\n *\n * @param options - The options for initializing the menu.\n */\n constructor(options) {\n super({ node: Private$9.createNode() });\n this._childIndex = -1;\n this._activeIndex = -1;\n this._openTimerID = 0;\n this._closeTimerID = 0;\n this._items = [];\n this._childMenu = null;\n this._parentMenu = null;\n this._aboutToClose = new Signal(this);\n this._menuRequested = new Signal(this);\n this.addClass('lm-Menu');\n this.setFlag(Widget.Flag.DisallowLayout);\n this.commands = options.commands;\n this.renderer = options.renderer || Menu.defaultRenderer;\n }\n /**\n * Dispose of the resources held by the menu.\n */\n dispose() {\n this.close();\n this._items.length = 0;\n super.dispose();\n }\n /**\n * A signal emitted just before the menu is closed.\n *\n * #### Notes\n * This signal is emitted when the menu receives a `'close-request'`\n * message, just before it removes itself from the DOM.\n *\n * This signal is not emitted if the menu is already detached from\n * the DOM when it receives the `'close-request'` message.\n */\n get aboutToClose() {\n return this._aboutToClose;\n }\n /**\n * A signal emitted when a new menu is requested by the user.\n *\n * #### Notes\n * This signal is emitted whenever the user presses the right or left\n * arrow keys, and a submenu cannot be opened or closed in response.\n *\n * This signal is useful when implementing menu bars in order to open\n * the next or previous menu in response to a user key press.\n *\n * This signal is only emitted for the root menu in a hierarchy.\n */\n get menuRequested() {\n return this._menuRequested;\n }\n /**\n * The parent menu of the menu.\n *\n * #### Notes\n * This is `null` unless the menu is an open submenu.\n */\n get parentMenu() {\n return this._parentMenu;\n }\n /**\n * The child menu of the menu.\n *\n * #### Notes\n * This is `null` unless the menu has an open submenu.\n */\n get childMenu() {\n return this._childMenu;\n }\n /**\n * The root menu of the menu hierarchy.\n */\n get rootMenu() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let menu = this;\n while (menu._parentMenu) {\n menu = menu._parentMenu;\n }\n return menu;\n }\n /**\n * The leaf menu of the menu hierarchy.\n */\n get leafMenu() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let menu = this;\n while (menu._childMenu) {\n menu = menu._childMenu;\n }\n return menu;\n }\n /**\n * The menu content node.\n *\n * #### Notes\n * This is the node which holds the menu item nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-Menu-content')[0];\n }\n /**\n * Get the currently active menu item.\n */\n get activeItem() {\n return this._items[this._activeIndex] || null;\n }\n /**\n * Set the currently active menu item.\n *\n * #### Notes\n * If the item cannot be activated, the item will be set to `null`.\n */\n set activeItem(value) {\n this.activeIndex = value ? this._items.indexOf(value) : -1;\n }\n /**\n * Get the index of the currently active menu item.\n *\n * #### Notes\n * This will be `-1` if no menu item is active.\n */\n get activeIndex() {\n return this._activeIndex;\n }\n /**\n * Set the index of the currently active menu item.\n *\n * #### Notes\n * If the item cannot be activated, the index will be set to `-1`.\n */\n set activeIndex(value) {\n // Adjust the value for an out of range index.\n if (value < 0 || value >= this._items.length) {\n value = -1;\n }\n // Ensure the item can be activated.\n if (value !== -1 && !Private$9.canActivate(this._items[value])) {\n value = -1;\n }\n // Bail if the index will not change.\n if (this._activeIndex === value) {\n return;\n }\n // Update the active index.\n this._activeIndex = value;\n // Make active element in focus\n if (this._activeIndex >= 0 &&\n this.contentNode.childNodes[this._activeIndex]) {\n this.contentNode.childNodes[this._activeIndex].focus();\n }\n // schedule an update of the items.\n this.update();\n }\n /**\n * A read-only array of the menu items in the menu.\n */\n get items() {\n return this._items;\n }\n /**\n * Activate the next selectable item in the menu.\n *\n * #### Notes\n * If no item is selectable, the index will be set to `-1`.\n */\n activateNextItem() {\n let n = this._items.length;\n let ai = this._activeIndex;\n let start = ai < n - 1 ? ai + 1 : 0;\n let stop = start === 0 ? n - 1 : start - 1;\n this.activeIndex = ArrayExt.findFirstIndex(this._items, Private$9.canActivate, start, stop);\n }\n /**\n * Activate the previous selectable item in the menu.\n *\n * #### Notes\n * If no item is selectable, the index will be set to `-1`.\n */\n activatePreviousItem() {\n let n = this._items.length;\n let ai = this._activeIndex;\n let start = ai <= 0 ? n - 1 : ai - 1;\n let stop = start === n - 1 ? 0 : start + 1;\n this.activeIndex = ArrayExt.findLastIndex(this._items, Private$9.canActivate, start, stop);\n }\n /**\n * Trigger the active menu item.\n *\n * #### Notes\n * If the active item is a submenu, it will be opened and the first\n * item will be activated.\n *\n * If the active item is a command, the command will be executed.\n *\n * If the menu is not attached, this is a no-op.\n *\n * If there is no active item, this is a no-op.\n */\n triggerActiveItem() {\n // Bail if the menu is not attached.\n if (!this.isAttached) {\n return;\n }\n // Bail if there is no active item.\n let item = this.activeItem;\n if (!item) {\n return;\n }\n // Cancel the pending timers.\n this._cancelOpenTimer();\n this._cancelCloseTimer();\n // If the item is a submenu, open it.\n if (item.type === 'submenu') {\n this._openChildMenu(true);\n return;\n }\n // Close the root menu before executing the command.\n this.rootMenu.close();\n // Execute the command for the item.\n let { command, args } = item;\n if (this.commands.isEnabled(command, args)) {\n this.commands.execute(command, args);\n }\n else {\n console.log(`Command '${command}' is disabled.`);\n }\n }\n /**\n * Add a menu item to the end of the menu.\n *\n * @param options - The options for creating the menu item.\n *\n * @returns The menu item added to the menu.\n */\n addItem(options) {\n return this.insertItem(this._items.length, options);\n }\n /**\n * Insert a menu item into the menu at the specified index.\n *\n * @param index - The index at which to insert the item.\n *\n * @param options - The options for creating the menu item.\n *\n * @returns The menu item added to the menu.\n *\n * #### Notes\n * The index will be clamped to the bounds of the items.\n */\n insertItem(index, options) {\n // Close the menu if it's attached.\n if (this.isAttached) {\n this.close();\n }\n // Reset the active index.\n this.activeIndex = -1;\n // Clamp the insert index to the array bounds.\n let i = Math.max(0, Math.min(index, this._items.length));\n // Create the item for the options.\n let item = Private$9.createItem(this, options);\n // Insert the item into the array.\n ArrayExt.insert(this._items, i, item);\n // Schedule an update of the items.\n this.update();\n // Return the item added to the menu.\n return item;\n }\n /**\n * Remove an item from the menu.\n *\n * @param item - The item to remove from the menu.\n *\n * #### Notes\n * This is a no-op if the item is not in the menu.\n */\n removeItem(item) {\n this.removeItemAt(this._items.indexOf(item));\n }\n /**\n * Remove the item at a given index from the menu.\n *\n * @param index - The index of the item to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeItemAt(index) {\n // Close the menu if it's attached.\n if (this.isAttached) {\n this.close();\n }\n // Reset the active index.\n this.activeIndex = -1;\n // Remove the item from the array.\n let item = ArrayExt.removeAt(this._items, index);\n // Bail if the index is out of range.\n if (!item) {\n return;\n }\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Remove all menu items from the menu.\n */\n clearItems() {\n // Close the menu if it's attached.\n if (this.isAttached) {\n this.close();\n }\n // Reset the active index.\n this.activeIndex = -1;\n // Bail if there is nothing to remove.\n if (this._items.length === 0) {\n return;\n }\n // Clear the items.\n this._items.length = 0;\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Open the menu at the specified location.\n *\n * @param x - The client X coordinate of the menu location.\n *\n * @param y - The client Y coordinate of the menu location.\n *\n * @param options - The additional options for opening the menu.\n *\n * #### Notes\n * The menu will be opened at the given location unless it will not\n * fully fit on the screen. If it will not fit, it will be adjusted\n * to fit naturally on the screen.\n *\n * This is a no-op if the menu is already attached to the DOM.\n */\n open(x, y, options = {}) {\n // Bail early if the menu is already attached.\n if (this.isAttached) {\n return;\n }\n // Extract the position options.\n let forceX = options.forceX || false;\n let forceY = options.forceY || false;\n // Open the menu as a root menu.\n Private$9.openRootMenu(this, x, y, forceX, forceY);\n // Activate the menu to accept keyboard input.\n this.activate();\n }\n /**\n * Handle the DOM events for the menu.\n *\n * @param event - The DOM event sent to the menu.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the menu's DOM nodes. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'mouseup':\n this._evtMouseUp(event);\n break;\n case 'mousemove':\n this._evtMouseMove(event);\n break;\n case 'mouseenter':\n this._evtMouseEnter(event);\n break;\n case 'mouseleave':\n this._evtMouseLeave(event);\n break;\n case 'mousedown':\n this._evtMouseDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('keydown', this);\n this.node.addEventListener('mouseup', this);\n this.node.addEventListener('mousemove', this);\n this.node.addEventListener('mouseenter', this);\n this.node.addEventListener('mouseleave', this);\n this.node.addEventListener('contextmenu', this);\n document.addEventListener('mousedown', this, true);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('keydown', this);\n this.node.removeEventListener('mouseup', this);\n this.node.removeEventListener('mousemove', this);\n this.node.removeEventListener('mouseenter', this);\n this.node.removeEventListener('mouseleave', this);\n this.node.removeEventListener('contextmenu', this);\n document.removeEventListener('mousedown', this, true);\n }\n /**\n * A message handler invoked on an `'activate-request'` message.\n */\n onActivateRequest(msg) {\n if (this.isAttached) {\n this.node.focus();\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n let items = this._items;\n let renderer = this.renderer;\n let activeIndex = this._activeIndex;\n let collapsedFlags = Private$9.computeCollapsed(items);\n let content = new Array(items.length);\n for (let i = 0, n = items.length; i < n; ++i) {\n let item = items[i];\n let active = i === activeIndex;\n let collapsed = collapsedFlags[i];\n content[i] = renderer.renderItem({\n item,\n active,\n collapsed,\n onfocus: () => {\n this.activeIndex = i;\n }\n });\n }\n VirtualDOM.render(content, this.contentNode);\n }\n /**\n * A message handler invoked on a `'close-request'` message.\n */\n onCloseRequest(msg) {\n // Cancel the pending timers.\n this._cancelOpenTimer();\n this._cancelCloseTimer();\n // Reset the active index.\n this.activeIndex = -1;\n // Close any open child menu.\n let childMenu = this._childMenu;\n if (childMenu) {\n this._childIndex = -1;\n this._childMenu = null;\n childMenu._parentMenu = null;\n childMenu.close();\n }\n // Remove this menu from its parent and activate the parent.\n let parentMenu = this._parentMenu;\n if (parentMenu) {\n this._parentMenu = null;\n parentMenu._childIndex = -1;\n parentMenu._childMenu = null;\n parentMenu.activate();\n }\n // Emit the `aboutToClose` signal if the menu is attached.\n if (this.isAttached) {\n this._aboutToClose.emit(undefined);\n }\n // Finish closing the menu.\n super.onCloseRequest(msg);\n }\n /**\n * Handle the `'keydown'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtKeyDown(event) {\n // A menu handles all keydown events.\n event.preventDefault();\n event.stopPropagation();\n // Fetch the key code for the event.\n let kc = event.keyCode;\n // Enter\n if (kc === 13) {\n this.triggerActiveItem();\n return;\n }\n // Escape\n if (kc === 27) {\n this.close();\n return;\n }\n // Left Arrow\n if (kc === 37) {\n if (this._parentMenu) {\n this.close();\n }\n else {\n this._menuRequested.emit('previous');\n }\n return;\n }\n // Up Arrow\n if (kc === 38) {\n this.activatePreviousItem();\n return;\n }\n // Right Arrow\n if (kc === 39) {\n let item = this.activeItem;\n if (item && item.type === 'submenu') {\n this.triggerActiveItem();\n }\n else {\n this.rootMenu._menuRequested.emit('next');\n }\n return;\n }\n // Down Arrow\n if (kc === 40) {\n this.activateNextItem();\n return;\n }\n // Get the pressed key character.\n let key = getKeyboardLayout().keyForKeydownEvent(event);\n // Bail if the key is not valid.\n if (!key) {\n return;\n }\n // Search for the next best matching mnemonic item.\n let start = this._activeIndex + 1;\n let result = Private$9.findMnemonic(this._items, key, start);\n // Handle the requested mnemonic based on the search results.\n // If exactly one mnemonic is matched, that item is triggered.\n // Otherwise, the next mnemonic is activated if available,\n // followed by the auto mnemonic if available.\n if (result.index !== -1 && !result.multiple) {\n this.activeIndex = result.index;\n this.triggerActiveItem();\n }\n else if (result.index !== -1) {\n this.activeIndex = result.index;\n }\n else if (result.auto !== -1) {\n this.activeIndex = result.auto;\n }\n }\n /**\n * Handle the `'mouseup'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseUp(event) {\n if (event.button !== 0) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n this.triggerActiveItem();\n }\n /**\n * Handle the `'mousemove'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseMove(event) {\n // Hit test the item nodes for the item under the mouse.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return ElementExt.hitTest(node, event.clientX, event.clientY);\n });\n // Bail early if the mouse is already over the active index.\n if (index === this._activeIndex) {\n return;\n }\n // Update and coerce the active index.\n this.activeIndex = index;\n index = this.activeIndex;\n // If the index is the current child index, cancel the timers.\n if (index === this._childIndex) {\n this._cancelOpenTimer();\n this._cancelCloseTimer();\n return;\n }\n // If a child menu is currently open, start the close timer.\n if (this._childIndex !== -1) {\n this._startCloseTimer();\n }\n // Cancel the open timer to give a full delay for opening.\n this._cancelOpenTimer();\n // Bail if the active item is not a valid submenu item.\n let item = this.activeItem;\n if (!item || item.type !== 'submenu' || !item.submenu) {\n return;\n }\n // Start the open timer to open the active item submenu.\n this._startOpenTimer();\n }\n /**\n * Handle the `'mouseenter'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseEnter(event) {\n // Synchronize the active ancestor items.\n for (let menu = this._parentMenu; menu; menu = menu._parentMenu) {\n menu._cancelOpenTimer();\n menu._cancelCloseTimer();\n menu.activeIndex = menu._childIndex;\n }\n }\n /**\n * Handle the `'mouseleave'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the menu node.\n */\n _evtMouseLeave(event) {\n // Cancel any pending submenu opening.\n this._cancelOpenTimer();\n // If there is no open child menu, just reset the active index.\n if (!this._childMenu) {\n this.activeIndex = -1;\n return;\n }\n // If the mouse is over the child menu, cancel the close timer.\n let { clientX, clientY } = event;\n if (ElementExt.hitTest(this._childMenu.node, clientX, clientY)) {\n this._cancelCloseTimer();\n return;\n }\n // Otherwise, reset the active index and start the close timer.\n this.activeIndex = -1;\n this._startCloseTimer();\n }\n /**\n * Handle the `'mousedown'` event for the menu.\n *\n * #### Notes\n * This listener is attached to the document node.\n */\n _evtMouseDown(event) {\n // Bail if the menu is not a root menu.\n if (this._parentMenu) {\n return;\n }\n // The mouse button which is pressed is irrelevant. If the press\n // is not on a menu, the entire hierarchy is closed and the event\n // is allowed to propagate. This allows other code to act on the\n // event, such as focusing the clicked element.\n if (Private$9.hitTestMenus(this, event.clientX, event.clientY)) {\n event.preventDefault();\n event.stopPropagation();\n }\n else {\n this.close();\n }\n }\n /**\n * Open the child menu at the active index immediately.\n *\n * If a different child menu is already open, it will be closed,\n * even if the active item is not a valid submenu.\n */\n _openChildMenu(activateFirst = false) {\n // If the item is not a valid submenu, close the child menu.\n let item = this.activeItem;\n if (!item || item.type !== 'submenu' || !item.submenu) {\n this._closeChildMenu();\n return;\n }\n // Do nothing if the child menu will not change.\n let submenu = item.submenu;\n if (submenu === this._childMenu) {\n return;\n }\n // Prior to any DOM modifications save window data\n Menu.saveWindowData();\n // Ensure the current child menu is closed.\n this._closeChildMenu();\n // Update the private child state.\n this._childMenu = submenu;\n this._childIndex = this._activeIndex;\n // Set the parent menu reference for the child.\n submenu._parentMenu = this;\n // Ensure the menu is updated and lookup the item node.\n MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);\n let itemNode = this.contentNode.children[this._activeIndex];\n // Open the submenu at the active node.\n Private$9.openSubmenu(submenu, itemNode);\n // Activate the first item if desired.\n if (activateFirst) {\n submenu.activeIndex = -1;\n submenu.activateNextItem();\n }\n // Activate the child menu.\n submenu.activate();\n }\n /**\n * Close the child menu immediately.\n *\n * This is a no-op if a child menu is not open.\n */\n _closeChildMenu() {\n if (this._childMenu) {\n this._childMenu.close();\n }\n }\n /**\n * Start the open timer, unless it is already pending.\n */\n _startOpenTimer() {\n if (this._openTimerID === 0) {\n this._openTimerID = window.setTimeout(() => {\n this._openTimerID = 0;\n this._openChildMenu();\n }, Private$9.TIMER_DELAY);\n }\n }\n /**\n * Start the close timer, unless it is already pending.\n */\n _startCloseTimer() {\n if (this._closeTimerID === 0) {\n this._closeTimerID = window.setTimeout(() => {\n this._closeTimerID = 0;\n this._closeChildMenu();\n }, Private$9.TIMER_DELAY);\n }\n }\n /**\n * Cancel the open timer, if the timer is pending.\n */\n _cancelOpenTimer() {\n if (this._openTimerID !== 0) {\n clearTimeout(this._openTimerID);\n this._openTimerID = 0;\n }\n }\n /**\n * Cancel the close timer, if the timer is pending.\n */\n _cancelCloseTimer() {\n if (this._closeTimerID !== 0) {\n clearTimeout(this._closeTimerID);\n this._closeTimerID = 0;\n }\n }\n /**\n * Save window data used for menu positioning in transient cache.\n *\n * In order to avoid layout trashing it is recommended to invoke this\n * method immediately prior to opening the menu and any DOM modifications\n * (like closing previously visible menu, or adding a class to menu widget).\n *\n * The transient cache will be released upon `open()` call.\n */\n static saveWindowData() {\n Private$9.saveWindowData();\n }\n}\n/**\n * The namespace for the `Menu` class statics.\n */\n(function (Menu) {\n /**\n * The default implementation of `IRenderer`.\n *\n * #### Notes\n * Subclasses are free to reimplement rendering methods as needed.\n */\n class Renderer {\n /**\n * Render the virtual element for a menu item.\n *\n * @param data - The data to use for rendering the item.\n *\n * @returns A virtual element representing the item.\n */\n renderItem(data) {\n let className = this.createItemClass(data);\n let dataset = this.createItemDataset(data);\n let aria = this.createItemARIA(data);\n return h.li({\n className,\n dataset,\n tabindex: '0',\n onfocus: data.onfocus,\n ...aria\n }, this.renderIcon(data), this.renderLabel(data), this.renderShortcut(data), this.renderSubmenu(data));\n }\n /**\n * Render the icon element for a menu item.\n *\n * @param data - The data to use for rendering the icon.\n *\n * @returns A virtual element representing the item icon.\n */\n renderIcon(data) {\n let className = this.createIconClass(data);\n // If data.item.icon is undefined, it will be ignored.\n return h.div({ className }, data.item.icon, data.item.iconLabel);\n }\n /**\n * Render the label element for a menu item.\n *\n * @param data - The data to use for rendering the label.\n *\n * @returns A virtual element representing the item label.\n */\n renderLabel(data) {\n let content = this.formatLabel(data);\n return h.div({ className: 'lm-Menu-itemLabel' }, content);\n }\n /**\n * Render the shortcut element for a menu item.\n *\n * @param data - The data to use for rendering the shortcut.\n *\n * @returns A virtual element representing the item shortcut.\n */\n renderShortcut(data) {\n let content = this.formatShortcut(data);\n return h.div({ className: 'lm-Menu-itemShortcut' }, content);\n }\n /**\n * Render the submenu icon element for a menu item.\n *\n * @param data - The data to use for rendering the submenu icon.\n *\n * @returns A virtual element representing the submenu icon.\n */\n renderSubmenu(data) {\n return h.div({ className: 'lm-Menu-itemSubmenuIcon' });\n }\n /**\n * Create the class name for the menu item.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the menu item.\n */\n createItemClass(data) {\n // Setup the initial class name.\n let name = 'lm-Menu-item';\n // Add the boolean state classes.\n if (!data.item.isEnabled) {\n name += ' lm-mod-disabled';\n }\n if (data.item.isToggled) {\n name += ' lm-mod-toggled';\n }\n if (!data.item.isVisible) {\n name += ' lm-mod-hidden';\n }\n if (data.active) {\n name += ' lm-mod-active';\n }\n if (data.collapsed) {\n name += ' lm-mod-collapsed';\n }\n // Add the extra class.\n let extra = data.item.className;\n if (extra) {\n name += ` ${extra}`;\n }\n // Return the complete class name.\n return name;\n }\n /**\n * Create the dataset for the menu item.\n *\n * @param data - The data to use for creating the dataset.\n *\n * @returns The dataset for the menu item.\n */\n createItemDataset(data) {\n let result;\n let { type, command, dataset } = data.item;\n if (type === 'command') {\n result = { ...dataset, type, command };\n }\n else {\n result = { ...dataset, type };\n }\n return result;\n }\n /**\n * Create the class name for the menu item icon.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the item icon.\n */\n createIconClass(data) {\n let name = 'lm-Menu-itemIcon';\n let extra = data.item.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n /**\n * Create the aria attributes for menu item.\n *\n * @param data - The data to use for the aria attributes.\n *\n * @returns The aria attributes object for the item.\n */\n createItemARIA(data) {\n let aria = {};\n switch (data.item.type) {\n case 'separator':\n aria.role = 'presentation';\n break;\n case 'submenu':\n aria['aria-haspopup'] = 'true';\n if (!data.item.isEnabled) {\n aria['aria-disabled'] = 'true';\n }\n break;\n default:\n if (!data.item.isEnabled) {\n aria['aria-disabled'] = 'true';\n }\n aria.role = 'menuitem';\n }\n return aria;\n }\n /**\n * Create the render content for the label node.\n *\n * @param data - The data to use for the label content.\n *\n * @returns The content to add to the label node.\n */\n formatLabel(data) {\n // Fetch the label text and mnemonic index.\n let { label, mnemonic } = data.item;\n // If the index is out of range, do not modify the label.\n if (mnemonic < 0 || mnemonic >= label.length) {\n return label;\n }\n // Split the label into parts.\n let prefix = label.slice(0, mnemonic);\n let suffix = label.slice(mnemonic + 1);\n let char = label[mnemonic];\n // Wrap the mnemonic character in a span.\n let span = h.span({ className: 'lm-Menu-itemMnemonic' }, char);\n // Return the content parts.\n return [prefix, span, suffix];\n }\n /**\n * Create the render content for the shortcut node.\n *\n * @param data - The data to use for the shortcut content.\n *\n * @returns The content to add to the shortcut node.\n */\n formatShortcut(data) {\n let kb = data.item.keyBinding;\n return kb ? CommandRegistry.formatKeystroke(kb.keys) : null;\n }\n }\n Menu.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n Menu.defaultRenderer = new Renderer();\n})(Menu || (Menu = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$9;\n(function (Private) {\n /**\n * The ms delay for opening and closing a submenu.\n */\n Private.TIMER_DELAY = 300;\n /**\n * The horizontal pixel overlap for an open submenu.\n */\n Private.SUBMENU_OVERLAP = 3;\n let transientWindowDataCache = null;\n let transientCacheCounter = 0;\n function getWindowData() {\n // if transient cache is in use, take one from it\n if (transientCacheCounter > 0) {\n transientCacheCounter--;\n return transientWindowDataCache;\n }\n return _getWindowData();\n }\n /**\n * Store window data in transient cache.\n *\n * The transient cache will be released upon `getWindowData()` call.\n * If this function is called multiple times, the cache will be\n * retained until as many calls to `getWindowData()` were made.\n *\n * Note: should be called before any DOM modifications.\n */\n function saveWindowData() {\n transientWindowDataCache = _getWindowData();\n transientCacheCounter++;\n }\n Private.saveWindowData = saveWindowData;\n /**\n * Create the DOM node for a menu.\n */\n function createNode() {\n let node = document.createElement('div');\n let content = document.createElement('ul');\n content.className = 'lm-Menu-content';\n node.appendChild(content);\n content.setAttribute('role', 'menu');\n node.tabIndex = 0;\n return node;\n }\n Private.createNode = createNode;\n /**\n * Test whether a menu item can be activated.\n */\n function canActivate(item) {\n return item.type !== 'separator' && item.isEnabled && item.isVisible;\n }\n Private.canActivate = canActivate;\n /**\n * Create a new menu item for an owner menu.\n */\n function createItem(owner, options) {\n return new MenuItem(owner.commands, options);\n }\n Private.createItem = createItem;\n /**\n * Hit test a menu hierarchy starting at the given root.\n */\n function hitTestMenus(menu, x, y) {\n for (let temp = menu; temp; temp = temp.childMenu) {\n if (ElementExt.hitTest(temp.node, x, y)) {\n return true;\n }\n }\n return false;\n }\n Private.hitTestMenus = hitTestMenus;\n /**\n * Compute which extra separator items should be collapsed.\n */\n function computeCollapsed(items) {\n // Allocate the return array and fill it with `false`.\n let result = new Array(items.length);\n ArrayExt.fill(result, false);\n // Collapse the leading separators.\n let k1 = 0;\n let n = items.length;\n for (; k1 < n; ++k1) {\n let item = items[k1];\n if (!item.isVisible) {\n continue;\n }\n if (item.type !== 'separator') {\n break;\n }\n result[k1] = true;\n }\n // Hide the trailing separators.\n let k2 = n - 1;\n for (; k2 >= 0; --k2) {\n let item = items[k2];\n if (!item.isVisible) {\n continue;\n }\n if (item.type !== 'separator') {\n break;\n }\n result[k2] = true;\n }\n // Hide the remaining consecutive separators.\n let hide = false;\n while (++k1 < k2) {\n let item = items[k1];\n if (!item.isVisible) {\n continue;\n }\n if (item.type !== 'separator') {\n hide = false;\n }\n else if (hide) {\n result[k1] = true;\n }\n else {\n hide = true;\n }\n }\n // Return the resulting flags.\n return result;\n }\n Private.computeCollapsed = computeCollapsed;\n function _getWindowData() {\n return {\n pageXOffset: window.pageXOffset,\n pageYOffset: window.pageYOffset,\n clientWidth: document.documentElement.clientWidth,\n clientHeight: document.documentElement.clientHeight\n };\n }\n /**\n * Open a menu as a root menu at the target location.\n */\n function openRootMenu(menu, x, y, forceX, forceY) {\n // Get the current position and size of the main viewport.\n const windowData = getWindowData();\n let px = windowData.pageXOffset;\n let py = windowData.pageYOffset;\n let cw = windowData.clientWidth;\n let ch = windowData.clientHeight;\n // Ensure the menu is updated before attaching and measuring.\n MessageLoop.sendMessage(menu, Widget.Msg.UpdateRequest);\n // Compute the maximum allowed height for the menu.\n let maxHeight = ch - (forceY ? y : 0);\n // Fetch common variables.\n let node = menu.node;\n let style = node.style;\n // Clear the menu geometry and prepare it for measuring.\n style.opacity = '0';\n style.maxHeight = `${maxHeight}px`;\n // Attach the menu to the document.\n Widget.attach(menu, document.body);\n // Measure the size of the menu.\n let { width, height } = node.getBoundingClientRect();\n // Adjust the X position of the menu to fit on-screen.\n if (!forceX && x + width > px + cw) {\n x = px + cw - width;\n }\n // Adjust the Y position of the menu to fit on-screen.\n if (!forceY && y + height > py + ch) {\n if (y > py + ch) {\n y = py + ch - height;\n }\n else {\n y = y - height;\n }\n }\n // Update the position of the menu to the computed position.\n style.transform = `translate(${Math.max(0, x)}px, ${Math.max(0, y)}px`;\n // Finally, make the menu visible on the screen.\n style.opacity = '1';\n }\n Private.openRootMenu = openRootMenu;\n /**\n * Open a menu as a submenu using an item node for positioning.\n */\n function openSubmenu(submenu, itemNode) {\n // Get the current position and size of the main viewport.\n const windowData = getWindowData();\n let px = windowData.pageXOffset;\n let py = windowData.pageYOffset;\n let cw = windowData.clientWidth;\n let ch = windowData.clientHeight;\n // Ensure the menu is updated before opening.\n MessageLoop.sendMessage(submenu, Widget.Msg.UpdateRequest);\n // Compute the maximum allowed height for the menu.\n let maxHeight = ch;\n // Fetch common variables.\n let node = submenu.node;\n let style = node.style;\n // Clear the menu geometry and prepare it for measuring.\n style.opacity = '0';\n style.maxHeight = `${maxHeight}px`;\n // Attach the menu to the document.\n Widget.attach(submenu, document.body);\n // Measure the size of the menu.\n let { width, height } = node.getBoundingClientRect();\n // Compute the box sizing for the menu.\n let box = ElementExt.boxSizing(submenu.node);\n // Get the bounding rect for the target item node.\n let itemRect = itemNode.getBoundingClientRect();\n // Compute the target X position.\n let x = itemRect.right - Private.SUBMENU_OVERLAP;\n // Adjust the X position to fit on the screen.\n if (x + width > px + cw) {\n x = itemRect.left + Private.SUBMENU_OVERLAP - width;\n }\n // Compute the target Y position.\n let y = itemRect.top - box.borderTop - box.paddingTop;\n // Adjust the Y position to fit on the screen.\n if (y + height > py + ch) {\n y = itemRect.bottom + box.borderBottom + box.paddingBottom - height;\n }\n // Update the position of the menu to the computed position.\n style.transform = `translate(${Math.max(0, x)}px, ${Math.max(0, y)}px`;\n // Finally, make the menu visible on the screen.\n style.opacity = '1';\n }\n Private.openSubmenu = openSubmenu;\n /**\n * Find the best matching mnemonic item.\n *\n * The search starts at the given index and wraps around.\n */\n function findMnemonic(items, key, start) {\n // Setup the result variables.\n let index = -1;\n let auto = -1;\n let multiple = false;\n // Normalize the key to upper case.\n let upperKey = key.toUpperCase();\n // Search the items from the given start index.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Compute the wrapped index.\n let k = (i + start) % n;\n // Lookup the item\n let item = items[k];\n // Ignore items which cannot be activated.\n if (!canActivate(item)) {\n continue;\n }\n // Ignore items with an empty label.\n let label = item.label;\n if (label.length === 0) {\n continue;\n }\n // Lookup the mnemonic index for the label.\n let mn = item.mnemonic;\n // Handle a valid mnemonic index.\n if (mn >= 0 && mn < label.length) {\n if (label[mn].toUpperCase() === upperKey) {\n if (index === -1) {\n index = k;\n }\n else {\n multiple = true;\n }\n }\n continue;\n }\n // Finally, handle the auto index if possible.\n if (auto === -1 && label[0].toUpperCase() === upperKey) {\n auto = k;\n }\n }\n // Return the search results.\n return { index, multiple, auto };\n }\n Private.findMnemonic = findMnemonic;\n /**\n * A concrete implementation of `Menu.IItem`.\n */\n class MenuItem {\n /**\n * Construct a new menu item.\n */\n constructor(commands, options) {\n this._commands = commands;\n this.type = options.type || 'command';\n this.command = options.command || '';\n this.args = options.args || JSONExt.emptyObject;\n this.submenu = options.submenu || null;\n }\n /**\n * The display label for the menu item.\n */\n get label() {\n if (this.type === 'command') {\n return this._commands.label(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.label;\n }\n return '';\n }\n /**\n * The mnemonic index for the menu item.\n */\n get mnemonic() {\n if (this.type === 'command') {\n return this._commands.mnemonic(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.mnemonic;\n }\n return -1;\n }\n /**\n * The icon renderer for the menu item.\n */\n get icon() {\n if (this.type === 'command') {\n return this._commands.icon(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.icon;\n }\n return undefined;\n }\n /**\n * The icon class for the menu item.\n */\n get iconClass() {\n if (this.type === 'command') {\n return this._commands.iconClass(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.iconClass;\n }\n return '';\n }\n /**\n * The icon label for the menu item.\n */\n get iconLabel() {\n if (this.type === 'command') {\n return this._commands.iconLabel(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.iconLabel;\n }\n return '';\n }\n /**\n * The display caption for the menu item.\n */\n get caption() {\n if (this.type === 'command') {\n return this._commands.caption(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.caption;\n }\n return '';\n }\n /**\n * The extra class name for the menu item.\n */\n get className() {\n if (this.type === 'command') {\n return this._commands.className(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.className;\n }\n return '';\n }\n /**\n * The dataset for the menu item.\n */\n get dataset() {\n if (this.type === 'command') {\n return this._commands.dataset(this.command, this.args);\n }\n if (this.type === 'submenu' && this.submenu) {\n return this.submenu.title.dataset;\n }\n return {};\n }\n /**\n * Whether the menu item is enabled.\n */\n get isEnabled() {\n if (this.type === 'command') {\n return this._commands.isEnabled(this.command, this.args);\n }\n if (this.type === 'submenu') {\n return this.submenu !== null;\n }\n return true;\n }\n /**\n * Whether the menu item is toggled.\n */\n get isToggled() {\n if (this.type === 'command') {\n return this._commands.isToggled(this.command, this.args);\n }\n return false;\n }\n /**\n * Whether the menu item is visible.\n */\n get isVisible() {\n if (this.type === 'command') {\n return this._commands.isVisible(this.command, this.args);\n }\n if (this.type === 'submenu') {\n return this.submenu !== null;\n }\n return true;\n }\n /**\n * The key binding for the menu item.\n */\n get keyBinding() {\n if (this.type === 'command') {\n let { command, args } = this;\n return (ArrayExt.findLastValue(this._commands.keyBindings, kb => {\n return kb.command === command && JSONExt.deepEqual(kb.args, args);\n }) || null);\n }\n return null;\n }\n }\n})(Private$9 || (Private$9 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * An object which implements a universal context menu.\n *\n * #### Notes\n * The items shown in the context menu are determined by CSS selector\n * matching against the DOM hierarchy at the site of the mouse click.\n * This is similar in concept to how keyboard shortcuts are matched\n * in the command registry.\n */\nclass ContextMenu {\n /**\n * Construct a new context menu.\n *\n * @param options - The options for initializing the menu.\n */\n constructor(options) {\n this._groupByTarget = true;\n this._idTick = 0;\n this._items = [];\n this._sortBySelector = true;\n const { groupByTarget, sortBySelector, ...others } = options;\n this.menu = new Menu(others);\n this._groupByTarget = groupByTarget !== false;\n this._sortBySelector = sortBySelector !== false;\n }\n /**\n * Add an item to the context menu.\n *\n * @param options - The options for creating the item.\n *\n * @returns A disposable which will remove the item from the menu.\n */\n addItem(options) {\n // Create an item from the given options.\n let item = Private$8.createItem(options, this._idTick++);\n // Add the item to the internal array.\n this._items.push(item);\n // Return a disposable which will remove the item.\n return new DisposableDelegate(() => {\n ArrayExt.removeFirstOf(this._items, item);\n });\n }\n /**\n * Open the context menu in response to a `'contextmenu'` event.\n *\n * @param event - The `'contextmenu'` event of interest.\n *\n * @returns `true` if the menu was opened, or `false` if no items\n * matched the event and the menu was not opened.\n *\n * #### Notes\n * This method will populate the context menu with items which match\n * the propagation path of the event, then open the menu at the mouse\n * position indicated by the event.\n */\n open(event) {\n // Prior to any DOM modifications update the window data.\n Menu.saveWindowData();\n // Clear the current contents of the context menu.\n this.menu.clearItems();\n // Bail early if there are no items to match.\n if (this._items.length === 0) {\n return false;\n }\n // Find the matching items for the event.\n let items = Private$8.matchItems(this._items, event, this._groupByTarget, this._sortBySelector);\n // Bail if there are no matching items.\n if (!items || items.length === 0) {\n return false;\n }\n // Add the filtered items to the menu.\n for (const item of items) {\n this.menu.addItem(item);\n }\n // Open the context menu at the current mouse position.\n this.menu.open(event.clientX, event.clientY);\n // Indicate success.\n return true;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$8;\n(function (Private) {\n /**\n * Create a normalized context menu item from an options object.\n */\n function createItem(options, id) {\n let selector = validateSelector(options.selector);\n let rank = options.rank !== undefined ? options.rank : Infinity;\n return { ...options, selector, rank, id };\n }\n Private.createItem = createItem;\n /**\n * Find the items which match a context menu event.\n *\n * The results are sorted by DOM level, specificity, and rank.\n */\n function matchItems(items, event, groupByTarget, sortBySelector) {\n // Look up the target of the event.\n let target = event.target;\n // Bail if there is no target.\n if (!target) {\n return null;\n }\n // Look up the current target of the event.\n let currentTarget = event.currentTarget;\n // Bail if there is no current target.\n if (!currentTarget) {\n return null;\n }\n // There are some third party libraries that cause the `target` to\n // be detached from the DOM before lumino can process the event.\n // If that happens, search for a new target node by point. If that\n // node is still dangling, bail.\n if (!currentTarget.contains(target)) {\n target = document.elementFromPoint(event.clientX, event.clientY);\n if (!target || !currentTarget.contains(target)) {\n return null;\n }\n }\n // Set up the result array.\n let result = [];\n // Copy the items array to allow in-place modification.\n let availableItems = items.slice();\n // Walk up the DOM hierarchy searching for matches.\n while (target !== null) {\n // Set up the match array for this DOM level.\n let matches = [];\n // Search the remaining items for matches.\n for (let i = 0, n = availableItems.length; i < n; ++i) {\n // Fetch the item.\n let item = availableItems[i];\n // Skip items which are already consumed.\n if (!item) {\n continue;\n }\n // Skip items which do not match the element.\n if (!Selector.matches(target, item.selector)) {\n continue;\n }\n // Add the matched item to the result for this DOM level.\n matches.push(item);\n // Mark the item as consumed.\n availableItems[i] = null;\n }\n // Sort the matches for this level and add them to the results.\n if (matches.length !== 0) {\n if (groupByTarget) {\n matches.sort(sortBySelector ? itemCmp : itemCmpRank);\n }\n result.push(...matches);\n }\n // Stop searching at the limits of the DOM range.\n if (target === currentTarget) {\n break;\n }\n // Step to the parent DOM level.\n target = target.parentElement;\n }\n if (!groupByTarget) {\n result.sort(sortBySelector ? itemCmp : itemCmpRank);\n }\n // Return the matched and sorted results.\n return result;\n }\n Private.matchItems = matchItems;\n /**\n * Validate the selector for a menu item.\n *\n * This returns the validated selector, or throws if the selector is\n * invalid or contains commas.\n */\n function validateSelector(selector) {\n if (selector.indexOf(',') !== -1) {\n throw new Error(`Selector cannot contain commas: ${selector}`);\n }\n if (!Selector.isValid(selector)) {\n throw new Error(`Invalid selector: ${selector}`);\n }\n return selector;\n }\n /**\n * A sort comparison function for a context menu item by ranks.\n */\n function itemCmpRank(a, b) {\n // Sort based on rank.\n let r1 = a.rank;\n let r2 = b.rank;\n if (r1 !== r2) {\n return r1 < r2 ? -1 : 1; // Infinity-safe\n }\n // When all else fails, sort by item id.\n return a.id - b.id;\n }\n /**\n * A sort comparison function for a context menu item by selectors and ranks.\n */\n function itemCmp(a, b) {\n // Sort first based on selector specificity.\n let s1 = Selector.calculateSpecificity(a.selector);\n let s2 = Selector.calculateSpecificity(b.selector);\n if (s1 !== s2) {\n return s2 - s1;\n }\n // If specificities are equal\n return itemCmpRank(a, b);\n }\n})(Private$8 || (Private$8 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nconst ARROW_KEYS = [\n 'ArrowLeft',\n 'ArrowUp',\n 'ArrowRight',\n 'ArrowDown',\n 'Home',\n 'End'\n];\n/**\n * A widget which displays titles as a single row or column of tabs.\n *\n * #### Notes\n * If CSS transforms are used to rotate nodes for vertically oriented\n * text, then tab dragging will not work correctly. The `tabsMovable`\n * property should be set to `false` when rotating nodes from CSS.\n */\nclass TabBar extends Widget {\n /**\n * Construct a new tab bar.\n *\n * @param options - The options for initializing the tab bar.\n */\n constructor(options = {}) {\n super({ node: Private$7.createNode() });\n this._currentIndex = -1;\n this._titles = [];\n this._titlesEditable = false;\n this._previousTitle = null;\n this._dragData = null;\n this._addButtonEnabled = false;\n this._tabMoved = new Signal(this);\n this._currentChanged = new Signal(this);\n this._addRequested = new Signal(this);\n this._tabCloseRequested = new Signal(this);\n this._tabDetachRequested = new Signal(this);\n this._tabActivateRequested = new Signal(this);\n this.addClass('lm-TabBar');\n this.contentNode.setAttribute('role', 'tablist');\n this.setFlag(Widget.Flag.DisallowLayout);\n this._document = options.document || document;\n this.tabsMovable = options.tabsMovable || false;\n this.titlesEditable = options.titlesEditable || false;\n this.allowDeselect = options.allowDeselect || false;\n this.addButtonEnabled = options.addButtonEnabled || false;\n this.insertBehavior = options.insertBehavior || 'select-tab-if-needed';\n this.name = options.name || '';\n this.orientation = options.orientation || 'horizontal';\n this.removeBehavior = options.removeBehavior || 'select-tab-after';\n this.renderer = options.renderer || TabBar.defaultRenderer;\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n this._releaseMouse();\n this._titles.length = 0;\n this._previousTitle = null;\n super.dispose();\n }\n /**\n * A signal emitted when the current tab is changed.\n *\n * #### Notes\n * This signal is emitted when the currently selected tab is changed\n * either through user or programmatic interaction.\n *\n * Notably, this signal is not emitted when the index of the current\n * tab changes due to tabs being inserted, removed, or moved. It is\n * only emitted when the actual current tab node is changed.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * A signal emitted when a tab is moved by the user.\n *\n * #### Notes\n * This signal is emitted when a tab is moved by user interaction.\n *\n * This signal is not emitted when a tab is moved programmatically.\n */\n get tabMoved() {\n return this._tabMoved;\n }\n /**\n * A signal emitted when a tab is clicked by the user.\n *\n * #### Notes\n * If the clicked tab is not the current tab, the clicked tab will be\n * made current and the `currentChanged` signal will be emitted first.\n *\n * This signal is emitted even if the clicked tab is the current tab.\n */\n get tabActivateRequested() {\n return this._tabActivateRequested;\n }\n /**\n * A signal emitted when the tab bar add button is clicked.\n */\n get addRequested() {\n return this._addRequested;\n }\n /**\n * A signal emitted when a tab close icon is clicked.\n *\n * #### Notes\n * This signal is not emitted unless the tab title is `closable`.\n */\n get tabCloseRequested() {\n return this._tabCloseRequested;\n }\n /**\n * A signal emitted when a tab is dragged beyond the detach threshold.\n *\n * #### Notes\n * This signal is emitted when the user drags a tab with the mouse,\n * and mouse is dragged beyond the detach threshold.\n *\n * The consumer of the signal should call `releaseMouse` and remove\n * the tab in order to complete the detach.\n *\n * This signal is only emitted once per drag cycle.\n */\n get tabDetachRequested() {\n return this._tabDetachRequested;\n }\n /**\n * The document to use with the tab bar.\n *\n * The default is the global `document` instance.\n */\n get document() {\n return this._document;\n }\n /**\n * Whether the titles can be user-edited.\n *\n */\n get titlesEditable() {\n return this._titlesEditable;\n }\n /**\n * Set whether titles can be user edited.\n *\n */\n set titlesEditable(value) {\n this._titlesEditable = value;\n }\n /**\n * Get the currently selected title.\n *\n * #### Notes\n * This will be `null` if no tab is selected.\n */\n get currentTitle() {\n return this._titles[this._currentIndex] || null;\n }\n /**\n * Set the currently selected title.\n *\n * #### Notes\n * If the title does not exist, the title will be set to `null`.\n */\n set currentTitle(value) {\n this.currentIndex = value ? this._titles.indexOf(value) : -1;\n }\n /**\n * Get the index of the currently selected tab.\n *\n * #### Notes\n * This will be `-1` if no tab is selected.\n */\n get currentIndex() {\n return this._currentIndex;\n }\n /**\n * Set the index of the currently selected tab.\n *\n * #### Notes\n * If the value is out of range, the index will be set to `-1`.\n */\n set currentIndex(value) {\n // Adjust for an out of range index.\n if (value < 0 || value >= this._titles.length) {\n value = -1;\n }\n // Bail early if the index will not change.\n if (this._currentIndex === value) {\n return;\n }\n // Look up the previous index and title.\n let pi = this._currentIndex;\n let pt = this._titles[pi] || null;\n // Look up the current index and title.\n let ci = value;\n let ct = this._titles[ci] || null;\n // Update the current index and previous title.\n this._currentIndex = ci;\n this._previousTitle = pt;\n // Schedule an update of the tabs.\n this.update();\n // Emit the current changed signal.\n this._currentChanged.emit({\n previousIndex: pi,\n previousTitle: pt,\n currentIndex: ci,\n currentTitle: ct\n });\n }\n /**\n * Get the name of the tab bar.\n */\n get name() {\n return this._name;\n }\n /**\n * Set the name of the tab bar.\n */\n set name(value) {\n this._name = value;\n if (value) {\n this.contentNode.setAttribute('aria-label', value);\n }\n else {\n this.contentNode.removeAttribute('aria-label');\n }\n }\n /**\n * Get the orientation of the tab bar.\n *\n * #### Notes\n * This controls whether the tabs are arranged in a row or column.\n */\n get orientation() {\n return this._orientation;\n }\n /**\n * Set the orientation of the tab bar.\n *\n * #### Notes\n * This controls whether the tabs are arranged in a row or column.\n */\n set orientation(value) {\n // Do nothing if the orientation does not change.\n if (this._orientation === value) {\n return;\n }\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Toggle the orientation values.\n this._orientation = value;\n this.dataset['orientation'] = value;\n this.contentNode.setAttribute('aria-orientation', value);\n }\n /**\n * Whether the add button is enabled.\n */\n get addButtonEnabled() {\n return this._addButtonEnabled;\n }\n /**\n * Set whether the add button is enabled.\n */\n set addButtonEnabled(value) {\n // Do nothing if the value does not change.\n if (this._addButtonEnabled === value) {\n return;\n }\n this._addButtonEnabled = value;\n if (value) {\n this.addButtonNode.classList.remove('lm-mod-hidden');\n }\n else {\n this.addButtonNode.classList.add('lm-mod-hidden');\n }\n }\n /**\n * A read-only array of the titles in the tab bar.\n */\n get titles() {\n return this._titles;\n }\n /**\n * The tab bar content node.\n *\n * #### Notes\n * This is the node which holds the tab nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-TabBar-content')[0];\n }\n /**\n * The tab bar add button node.\n *\n * #### Notes\n * This is the node which holds the add button.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get addButtonNode() {\n return this.node.getElementsByClassName('lm-TabBar-addButton')[0];\n }\n /**\n * Add a tab to the end of the tab bar.\n *\n * @param value - The title which holds the data for the tab,\n * or an options object to convert to a title.\n *\n * @returns The title object added to the tab bar.\n *\n * #### Notes\n * If the title is already added to the tab bar, it will be moved.\n */\n addTab(value) {\n return this.insertTab(this._titles.length, value);\n }\n /**\n * Insert a tab into the tab bar at the specified index.\n *\n * @param index - The index at which to insert the tab.\n *\n * @param value - The title which holds the data for the tab,\n * or an options object to convert to a title.\n *\n * @returns The title object added to the tab bar.\n *\n * #### Notes\n * The index will be clamped to the bounds of the tabs.\n *\n * If the title is already added to the tab bar, it will be moved.\n */\n insertTab(index, value) {\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Coerce the value to a title.\n let title = Private$7.asTitle(value);\n // Look up the index of the title.\n let i = this._titles.indexOf(title);\n // Clamp the insert index to the array bounds.\n let j = Math.max(0, Math.min(index, this._titles.length));\n // If the title is not in the array, insert it.\n if (i === -1) {\n // Insert the title into the array.\n ArrayExt.insert(this._titles, j, title);\n // Connect to the title changed signal.\n title.changed.connect(this._onTitleChanged, this);\n // Schedule an update of the tabs.\n this.update();\n // Adjust the current index for the insert.\n this._adjustCurrentForInsert(j, title);\n // Return the title added to the tab bar.\n return title;\n }\n // Otherwise, the title exists in the array and should be moved.\n // Adjust the index if the location is at the end of the array.\n if (j === this._titles.length) {\n j--;\n }\n // Bail if there is no effective move.\n if (i === j) {\n return title;\n }\n // Move the title to the new location.\n ArrayExt.move(this._titles, i, j);\n // Schedule an update of the tabs.\n this.update();\n // Adjust the current index for the move.\n this._adjustCurrentForMove(i, j);\n // Return the title added to the tab bar.\n return title;\n }\n /**\n * Remove a tab from the tab bar.\n *\n * @param title - The title for the tab to remove.\n *\n * #### Notes\n * This is a no-op if the title is not in the tab bar.\n */\n removeTab(title) {\n this.removeTabAt(this._titles.indexOf(title));\n }\n /**\n * Remove the tab at a given index from the tab bar.\n *\n * @param index - The index of the tab to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeTabAt(index) {\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Remove the title from the array.\n let title = ArrayExt.removeAt(this._titles, index);\n // Bail if the index is out of range.\n if (!title) {\n return;\n }\n // Disconnect from the title changed signal.\n title.changed.disconnect(this._onTitleChanged, this);\n // Clear the previous title if it's being removed.\n if (title === this._previousTitle) {\n this._previousTitle = null;\n }\n // Schedule an update of the tabs.\n this.update();\n // Adjust the current index for the remove.\n this._adjustCurrentForRemove(index, title);\n }\n /**\n * Remove all tabs from the tab bar.\n */\n clearTabs() {\n // Bail if there is nothing to remove.\n if (this._titles.length === 0) {\n return;\n }\n // Release the mouse before making any changes.\n this._releaseMouse();\n // Disconnect from the title changed signals.\n for (let title of this._titles) {\n title.changed.disconnect(this._onTitleChanged, this);\n }\n // Get the current index and title.\n let pi = this.currentIndex;\n let pt = this.currentTitle;\n // Reset the current index and previous title.\n this._currentIndex = -1;\n this._previousTitle = null;\n // Clear the title array.\n this._titles.length = 0;\n // Schedule an update of the tabs.\n this.update();\n // If no tab was selected, there's nothing else to do.\n if (pi === -1) {\n return;\n }\n // Emit the current changed signal.\n this._currentChanged.emit({\n previousIndex: pi,\n previousTitle: pt,\n currentIndex: -1,\n currentTitle: null\n });\n }\n /**\n * Release the mouse and restore the non-dragged tab positions.\n *\n * #### Notes\n * This will cause the tab bar to stop handling mouse events and to\n * restore the tabs to their non-dragged positions.\n */\n releaseMouse() {\n this._releaseMouse();\n }\n /**\n * Handle the DOM events for the tab bar.\n *\n * @param event - The DOM event sent to the tab bar.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the tab bar's DOM node.\n *\n * This should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'pointerdown':\n this._evtPointerDown(event);\n break;\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'dblclick':\n this._evtDblClick(event);\n break;\n case 'keydown':\n event.eventPhase === Event.CAPTURING_PHASE\n ? this._evtKeyDownCapturing(event)\n : this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('pointerdown', this);\n this.node.addEventListener('dblclick', this);\n this.node.addEventListener('keydown', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('pointerdown', this);\n this.node.removeEventListener('dblclick', this);\n this.node.removeEventListener('keydown', this);\n this._releaseMouse();\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n var _a;\n let titles = this._titles;\n let renderer = this.renderer;\n let currentTitle = this.currentTitle;\n let content = new Array(titles.length);\n // Keep the tabindex=\"0\" attribute to the tab which handled it before the update.\n // If the add button handles it, no need to do anything. If no element of the tab\n // bar handles it, set it on the current or the first tab to ensure one element\n // handles it after update.\n const tabHandlingTabindex = (_a = this._getCurrentTabindex()) !== null && _a !== void 0 ? _a : (this._currentIndex > -1 ? this._currentIndex : 0);\n for (let i = 0, n = titles.length; i < n; ++i) {\n let title = titles[i];\n let current = title === currentTitle;\n let zIndex = current ? n : n - i - 1;\n let tabIndex = tabHandlingTabindex === i ? 0 : -1;\n content[i] = renderer.renderTab({ title, current, zIndex, tabIndex });\n }\n VirtualDOM.render(content, this.contentNode);\n }\n /**\n * Get the index of the tab which handles tabindex=\"0\".\n * If the add button handles tabindex=\"0\", -1 is returned.\n * If none of the previous handles tabindex=\"0\", null is returned.\n */\n _getCurrentTabindex() {\n let index = null;\n const elemTabindex = this.contentNode.querySelector('li[tabindex=\"0\"]');\n if (elemTabindex) {\n index = [...this.contentNode.children].indexOf(elemTabindex);\n }\n else if (this._addButtonEnabled &&\n this.addButtonNode.getAttribute('tabindex') === '0') {\n index = -1;\n }\n return index;\n }\n /**\n * Handle the `'dblclick'` event for the tab bar.\n */\n _evtDblClick(event) {\n // Do nothing if titles are not editable\n if (!this.titlesEditable) {\n return;\n }\n let tabs = this.contentNode.children;\n // Find the index of the targeted tab.\n let index = ArrayExt.findFirstIndex(tabs, tab => {\n return ElementExt.hitTest(tab, event.clientX, event.clientY);\n });\n // Do nothing if the press is not on a tab.\n if (index === -1) {\n return;\n }\n let title = this.titles[index];\n let label = tabs[index].querySelector('.lm-TabBar-tabLabel');\n if (label && label.contains(event.target)) {\n let value = title.label || '';\n // Clear the label element\n let oldValue = label.innerHTML;\n label.innerHTML = '';\n let input = document.createElement('input');\n input.classList.add('lm-TabBar-tabInput');\n input.value = value;\n label.appendChild(input);\n let onblur = () => {\n input.removeEventListener('blur', onblur);\n label.innerHTML = oldValue;\n this.node.addEventListener('keydown', this);\n };\n input.addEventListener('dblclick', (event) => event.stopPropagation());\n input.addEventListener('blur', onblur);\n input.addEventListener('keydown', (event) => {\n if (event.key === 'Enter') {\n if (input.value !== '') {\n title.label = title.caption = input.value;\n }\n onblur();\n }\n else if (event.key === 'Escape') {\n onblur();\n }\n });\n this.node.removeEventListener('keydown', this);\n input.select();\n input.focus();\n if (label.children.length > 0) {\n label.children[0].focus();\n }\n }\n }\n /**\n * Handle the `'keydown'` event for the tab bar at capturing phase.\n */\n _evtKeyDownCapturing(event) {\n if (event.eventPhase !== Event.CAPTURING_PHASE) {\n return;\n }\n // Stop all input events during drag.\n event.preventDefault();\n event.stopPropagation();\n // Release the mouse if `Escape` is pressed.\n if (event.key === 'Escape') {\n this._releaseMouse();\n }\n }\n /**\n * Handle the `'keydown'` event for the tab bar at target phase.\n */\n _evtKeyDown(event) {\n var _a, _b, _c;\n // Allow for navigation using tab key\n if (event.key === 'Tab' || event.eventPhase === Event.CAPTURING_PHASE) {\n return;\n }\n // Check if Enter or Spacebar key has been pressed and open that tab\n if (event.key === 'Enter' ||\n event.key === 'Spacebar' ||\n event.key === ' ') {\n // Get focus element that is in focus by the tab key\n const focusedElement = document.activeElement;\n // Test first if the focus is on the add button node\n if (this.addButtonEnabled &&\n this.addButtonNode.contains(focusedElement)) {\n event.preventDefault();\n event.stopPropagation();\n this._addRequested.emit();\n }\n else {\n const index = ArrayExt.findFirstIndex(this.contentNode.children, tab => tab.contains(focusedElement));\n if (index >= 0) {\n event.preventDefault();\n event.stopPropagation();\n this.currentIndex = index;\n }\n }\n // Handle the arrow keys to switch tabs.\n }\n else if (ARROW_KEYS.includes(event.key)) {\n // Create a list of all focusable elements in the tab bar.\n const focusable = [...this.contentNode.children];\n if (this.addButtonEnabled) {\n focusable.push(this.addButtonNode);\n }\n // If the tab bar contains only one element, nothing to do.\n if (focusable.length <= 1) {\n return;\n }\n event.preventDefault();\n event.stopPropagation();\n // Get the current focused element.\n let focusedIndex = focusable.indexOf(document.activeElement);\n if (focusedIndex === -1) {\n focusedIndex = this._currentIndex;\n }\n // Find the next element to focus on.\n let nextFocused;\n if ((event.key === 'ArrowRight' && this._orientation === 'horizontal') ||\n (event.key === 'ArrowDown' && this._orientation === 'vertical')) {\n nextFocused = (_a = focusable[focusedIndex + 1]) !== null && _a !== void 0 ? _a : focusable[0];\n }\n else if ((event.key === 'ArrowLeft' && this._orientation === 'horizontal') ||\n (event.key === 'ArrowUp' && this._orientation === 'vertical')) {\n nextFocused =\n (_b = focusable[focusedIndex - 1]) !== null && _b !== void 0 ? _b : focusable[focusable.length - 1];\n }\n else if (event.key === 'Home') {\n nextFocused = focusable[0];\n }\n else if (event.key === 'End') {\n nextFocused = focusable[focusable.length - 1];\n }\n // Change the focused element and the tabindex value.\n if (nextFocused) {\n (_c = focusable[focusedIndex]) === null || _c === void 0 ? void 0 : _c.setAttribute('tabindex', '-1');\n nextFocused === null || nextFocused === void 0 ? void 0 : nextFocused.setAttribute('tabindex', '0');\n nextFocused.focus();\n }\n }\n }\n /**\n * Handle the `'pointerdown'` event for the tab bar.\n */\n _evtPointerDown(event) {\n // Do nothing if it's not a left or middle mouse press.\n if (event.button !== 0 && event.button !== 1) {\n return;\n }\n // Do nothing if a drag is in progress.\n if (this._dragData) {\n return;\n }\n // Do nothing if a title editable input was clicked.\n if (event.target.classList.contains('lm-TabBar-tabInput')) {\n return;\n }\n // Check if the add button was clicked.\n let addButtonClicked = this.addButtonEnabled &&\n this.addButtonNode.contains(event.target);\n // Lookup the tab nodes.\n let tabs = this.contentNode.children;\n // Find the index of the pressed tab.\n let index = ArrayExt.findFirstIndex(tabs, tab => {\n return ElementExt.hitTest(tab, event.clientX, event.clientY);\n });\n // Do nothing if the press is not on a tab or the add button.\n if (index === -1 && !addButtonClicked) {\n return;\n }\n // Pressing on a tab stops the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Initialize the non-measured parts of the drag data.\n this._dragData = {\n tab: tabs[index],\n index: index,\n pressX: event.clientX,\n pressY: event.clientY,\n tabPos: -1,\n tabSize: -1,\n tabPressPos: -1,\n targetIndex: -1,\n tabLayout: null,\n contentRect: null,\n override: null,\n dragActive: false,\n dragAborted: false,\n detachRequested: false\n };\n // Add the document pointer up listener.\n this.document.addEventListener('pointerup', this, true);\n // Do nothing else if the middle button or add button is clicked.\n if (event.button === 1 || addButtonClicked) {\n return;\n }\n // Do nothing else if the close icon is clicked.\n let icon = tabs[index].querySelector(this.renderer.closeIconSelector);\n if (icon && icon.contains(event.target)) {\n return;\n }\n // Add the extra listeners if the tabs are movable.\n if (this.tabsMovable) {\n this.document.addEventListener('pointermove', this, true);\n this.document.addEventListener('keydown', this, true);\n this.document.addEventListener('contextmenu', this, true);\n }\n // Update the current index as appropriate.\n if (this.allowDeselect && this.currentIndex === index) {\n this.currentIndex = -1;\n }\n else {\n this.currentIndex = index;\n }\n // Do nothing else if there is no current tab.\n if (this.currentIndex === -1) {\n return;\n }\n // Emit the tab activate request signal.\n this._tabActivateRequested.emit({\n index: this.currentIndex,\n title: this.currentTitle\n });\n }\n /**\n * Handle the `'pointermove'` event for the tab bar.\n */\n _evtPointerMove(event) {\n // Do nothing if no drag is in progress.\n let data = this._dragData;\n if (!data) {\n return;\n }\n // Suppress the event during a drag.\n event.preventDefault();\n event.stopPropagation();\n // Lookup the tab nodes.\n let tabs = this.contentNode.children;\n // Bail early if the drag threshold has not been met.\n if (!data.dragActive && !Private$7.dragExceeded(data, event)) {\n return;\n }\n // Activate the drag if necessary.\n if (!data.dragActive) {\n // Fill in the rest of the drag data measurements.\n let tabRect = data.tab.getBoundingClientRect();\n if (this._orientation === 'horizontal') {\n data.tabPos = data.tab.offsetLeft;\n data.tabSize = tabRect.width;\n data.tabPressPos = data.pressX - tabRect.left;\n }\n else {\n data.tabPos = data.tab.offsetTop;\n data.tabSize = tabRect.height;\n data.tabPressPos = data.pressY - tabRect.top;\n }\n data.tabPressOffset = {\n x: data.pressX - tabRect.left,\n y: data.pressY - tabRect.top\n };\n data.tabLayout = Private$7.snapTabLayout(tabs, this._orientation);\n data.contentRect = this.contentNode.getBoundingClientRect();\n data.override = Drag.overrideCursor('default');\n // Add the dragging style classes.\n data.tab.classList.add('lm-mod-dragging');\n this.addClass('lm-mod-dragging');\n // Mark the drag as active.\n data.dragActive = true;\n }\n // Emit the detach requested signal if the threshold is exceeded.\n if (!data.detachRequested && Private$7.detachExceeded(data, event)) {\n // Only emit the signal once per drag cycle.\n data.detachRequested = true;\n // Setup the arguments for the signal.\n let index = data.index;\n let clientX = event.clientX;\n let clientY = event.clientY;\n let tab = tabs[index];\n let title = this._titles[index];\n // Emit the tab detach requested signal.\n this._tabDetachRequested.emit({\n index,\n title,\n tab,\n clientX,\n clientY,\n offset: data.tabPressOffset\n });\n // Bail if the signal handler aborted the drag.\n if (data.dragAborted) {\n return;\n }\n }\n // Update the positions of the tabs.\n Private$7.layoutTabs(tabs, data, event, this._orientation);\n }\n /**\n * Handle the `'pointerup'` event for the document.\n */\n _evtPointerUp(event) {\n // Do nothing if it's not a left or middle mouse release.\n if (event.button !== 0 && event.button !== 1) {\n return;\n }\n // Do nothing if no drag is in progress.\n const data = this._dragData;\n if (!data) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Remove the extra mouse event listeners.\n this.document.removeEventListener('pointermove', this, true);\n this.document.removeEventListener('pointerup', this, true);\n this.document.removeEventListener('keydown', this, true);\n this.document.removeEventListener('contextmenu', this, true);\n // Handle a release when the drag is not active.\n if (!data.dragActive) {\n // Clear the drag data.\n this._dragData = null;\n // Handle clicking the add button.\n let addButtonClicked = this.addButtonEnabled &&\n this.addButtonNode.contains(event.target);\n if (addButtonClicked) {\n this._addRequested.emit(undefined);\n return;\n }\n // Lookup the tab nodes.\n let tabs = this.contentNode.children;\n // Find the index of the released tab.\n let index = ArrayExt.findFirstIndex(tabs, tab => {\n return ElementExt.hitTest(tab, event.clientX, event.clientY);\n });\n // Do nothing if the release is not on the original pressed tab.\n if (index !== data.index) {\n return;\n }\n // Ignore the release if the title is not closable.\n let title = this._titles[index];\n if (!title.closable) {\n return;\n }\n // Emit the close requested signal if the middle button is released.\n if (event.button === 1) {\n this._tabCloseRequested.emit({ index, title });\n return;\n }\n // Emit the close requested signal if the close icon was released.\n let icon = tabs[index].querySelector(this.renderer.closeIconSelector);\n if (icon && icon.contains(event.target)) {\n this._tabCloseRequested.emit({ index, title });\n return;\n }\n // Otherwise, there is nothing left to do.\n return;\n }\n // Do nothing if the left button is not released.\n if (event.button !== 0) {\n return;\n }\n // Position the tab at its final resting position.\n Private$7.finalizeTabPosition(data, this._orientation);\n // Remove the dragging class from the tab so it can be transitioned.\n data.tab.classList.remove('lm-mod-dragging');\n // Parse the transition duration for releasing the tab.\n let duration = Private$7.parseTransitionDuration(data.tab);\n // Complete the release on a timer to allow the tab to transition.\n setTimeout(() => {\n // Do nothing if the drag has been aborted.\n if (data.dragAborted) {\n return;\n }\n // Clear the drag data reference.\n this._dragData = null;\n // Reset the positions of the tabs.\n Private$7.resetTabPositions(this.contentNode.children, this._orientation);\n // Clear the cursor grab.\n data.override.dispose();\n // Remove the remaining dragging style.\n this.removeClass('lm-mod-dragging');\n // If the tab was not moved, there is nothing else to do.\n let i = data.index;\n let j = data.targetIndex;\n if (j === -1 || i === j) {\n return;\n }\n // Move the title to the new locations.\n ArrayExt.move(this._titles, i, j);\n // Adjust the current index for the move.\n this._adjustCurrentForMove(i, j);\n // Emit the tab moved signal.\n this._tabMoved.emit({\n fromIndex: i,\n toIndex: j,\n title: this._titles[j]\n });\n // Update the tabs immediately to prevent flicker.\n MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);\n }, duration);\n }\n /**\n * Release the mouse and restore the non-dragged tab positions.\n */\n _releaseMouse() {\n // Do nothing if no drag is in progress.\n let data = this._dragData;\n if (!data) {\n return;\n }\n // Clear the drag data reference.\n this._dragData = null;\n // Remove the extra document event listeners.\n this.document.removeEventListener('pointermove', this, true);\n this.document.removeEventListener('pointerup', this, true);\n this.document.removeEventListener('keydown', this, true);\n this.document.removeEventListener('contextmenu', this, true);\n // Indicate the drag has been aborted. This allows the mouse\n // event handlers to return early when the drag is canceled.\n data.dragAborted = true;\n // If the drag is not active, there's nothing more to do.\n if (!data.dragActive) {\n return;\n }\n // Reset the tabs to their non-dragged positions.\n Private$7.resetTabPositions(this.contentNode.children, this._orientation);\n // Clear the cursor override.\n data.override.dispose();\n // Clear the dragging style classes.\n data.tab.classList.remove('lm-mod-dragging');\n this.removeClass('lm-mod-dragging');\n }\n /**\n * Adjust the current index for a tab insert operation.\n *\n * This method accounts for the tab bar's insertion behavior when\n * adjusting the current index and emitting the changed signal.\n */\n _adjustCurrentForInsert(i, title) {\n // Lookup commonly used variables.\n let ct = this.currentTitle;\n let ci = this._currentIndex;\n let bh = this.insertBehavior;\n // TODO: do we need to do an update to update the aria-selected attribute?\n // Handle the behavior where the new tab is always selected,\n // or the behavior where the new tab is selected if needed.\n if (bh === 'select-tab' || (bh === 'select-tab-if-needed' && ci === -1)) {\n this._currentIndex = i;\n this._previousTitle = ct;\n this._currentChanged.emit({\n previousIndex: ci,\n previousTitle: ct,\n currentIndex: i,\n currentTitle: title\n });\n return;\n }\n // Otherwise, silently adjust the current index if needed.\n if (ci >= i) {\n this._currentIndex++;\n }\n }\n /**\n * Adjust the current index for a tab move operation.\n *\n * This method will not cause the actual current tab to change.\n * It silently adjusts the index to account for the given move.\n */\n _adjustCurrentForMove(i, j) {\n if (this._currentIndex === i) {\n this._currentIndex = j;\n }\n else if (this._currentIndex < i && this._currentIndex >= j) {\n this._currentIndex++;\n }\n else if (this._currentIndex > i && this._currentIndex <= j) {\n this._currentIndex--;\n }\n }\n /**\n * Adjust the current index for a tab remove operation.\n *\n * This method accounts for the tab bar's remove behavior when\n * adjusting the current index and emitting the changed signal.\n */\n _adjustCurrentForRemove(i, title) {\n // Lookup commonly used variables.\n let ci = this._currentIndex;\n let bh = this.removeBehavior;\n // Silently adjust the index if the current tab is not removed.\n if (ci !== i) {\n if (ci > i) {\n this._currentIndex--;\n }\n return;\n }\n // TODO: do we need to do an update to adjust the aria-selected value?\n // No tab gets selected if the tab bar is empty.\n if (this._titles.length === 0) {\n this._currentIndex = -1;\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: -1,\n currentTitle: null\n });\n return;\n }\n // Handle behavior where the next sibling tab is selected.\n if (bh === 'select-tab-after') {\n this._currentIndex = Math.min(i, this._titles.length - 1);\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: this._currentIndex,\n currentTitle: this.currentTitle\n });\n return;\n }\n // Handle behavior where the previous sibling tab is selected.\n if (bh === 'select-tab-before') {\n this._currentIndex = Math.max(0, i - 1);\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: this._currentIndex,\n currentTitle: this.currentTitle\n });\n return;\n }\n // Handle behavior where the previous history tab is selected.\n if (bh === 'select-previous-tab') {\n if (this._previousTitle) {\n this._currentIndex = this._titles.indexOf(this._previousTitle);\n this._previousTitle = null;\n }\n else {\n this._currentIndex = Math.min(i, this._titles.length - 1);\n }\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: this._currentIndex,\n currentTitle: this.currentTitle\n });\n return;\n }\n // Otherwise, no tab gets selected.\n this._currentIndex = -1;\n this._currentChanged.emit({\n previousIndex: i,\n previousTitle: title,\n currentIndex: -1,\n currentTitle: null\n });\n }\n /**\n * Handle the `changed` signal of a title object.\n */\n _onTitleChanged(sender) {\n this.update();\n }\n}\n/**\n * The namespace for the `TabBar` class statics.\n */\n(function (TabBar) {\n /**\n * The default implementation of `IRenderer`.\n *\n * #### Notes\n * Subclasses are free to reimplement rendering methods as needed.\n */\n class Renderer {\n constructor() {\n /**\n * A selector which matches the close icon node in a tab.\n */\n this.closeIconSelector = '.lm-TabBar-tabCloseIcon';\n this._tabID = 0;\n this._tabKeys = new WeakMap();\n this._uuid = ++Renderer._nInstance;\n }\n /**\n * Render the virtual element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab.\n */\n renderTab(data) {\n let title = data.title.caption;\n let key = this.createTabKey(data);\n let id = key;\n let style = this.createTabStyle(data);\n let className = this.createTabClass(data);\n let dataset = this.createTabDataset(data);\n let aria = this.createTabARIA(data);\n if (data.title.closable) {\n return h.li({ id, key, className, title, style, dataset, ...aria }, this.renderIcon(data), this.renderLabel(data), this.renderCloseIcon(data));\n }\n else {\n return h.li({ id, key, className, title, style, dataset, ...aria }, this.renderIcon(data), this.renderLabel(data));\n }\n }\n /**\n * Render the icon element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab icon.\n */\n renderIcon(data) {\n const { title } = data;\n let className = this.createIconClass(data);\n // If title.icon is undefined, it will be ignored.\n return h.div({ className }, title.icon, title.iconLabel);\n }\n /**\n * Render the label element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab label.\n */\n renderLabel(data) {\n return h.div({ className: 'lm-TabBar-tabLabel' }, data.title.label);\n }\n /**\n * Render the close icon element for a tab.\n *\n * @param data - The data to use for rendering the tab.\n *\n * @returns A virtual element representing the tab close icon.\n */\n renderCloseIcon(data) {\n return h.div({ className: 'lm-TabBar-tabCloseIcon' });\n }\n /**\n * Create a unique render key for the tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The unique render key for the tab.\n *\n * #### Notes\n * This method caches the key against the tab title the first time\n * the key is generated. This enables efficient rendering of moved\n * tabs and avoids subtle hover style artifacts.\n */\n createTabKey(data) {\n let key = this._tabKeys.get(data.title);\n if (key === undefined) {\n key = `tab-key-${this._uuid}-${this._tabID++}`;\n this._tabKeys.set(data.title, key);\n }\n return key;\n }\n /**\n * Create the inline style object for a tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The inline style data for the tab.\n */\n createTabStyle(data) {\n return { zIndex: `${data.zIndex}` };\n }\n /**\n * Create the class name for the tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The full class name for the tab.\n */\n createTabClass(data) {\n let name = 'lm-TabBar-tab';\n if (data.title.className) {\n name += ` ${data.title.className}`;\n }\n if (data.title.closable) {\n name += ' lm-mod-closable';\n }\n if (data.current) {\n name += ' lm-mod-current';\n }\n return name;\n }\n /**\n * Create the dataset for a tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The dataset for the tab.\n */\n createTabDataset(data) {\n return data.title.dataset;\n }\n /**\n * Create the ARIA attributes for a tab.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The ARIA attributes for the tab.\n */\n createTabARIA(data) {\n var _a;\n return {\n role: 'tab',\n 'aria-selected': data.current.toString(),\n tabindex: `${(_a = data.tabIndex) !== null && _a !== void 0 ? _a : '-1'}`\n };\n }\n /**\n * Create the class name for the tab icon.\n *\n * @param data - The data to use for the tab.\n *\n * @returns The full class name for the tab icon.\n */\n createIconClass(data) {\n let name = 'lm-TabBar-tabIcon';\n let extra = data.title.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n }\n Renderer._nInstance = 0;\n TabBar.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n TabBar.defaultRenderer = new Renderer();\n /**\n * A selector which matches the add button node in the tab bar.\n */\n TabBar.addButtonSelector = '.lm-TabBar-addButton';\n})(TabBar || (TabBar = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$7;\n(function (Private) {\n /**\n * The start drag distance threshold.\n */\n Private.DRAG_THRESHOLD = 5;\n /**\n * The detach distance threshold.\n */\n Private.DETACH_THRESHOLD = 20;\n /**\n * Create the DOM node for a tab bar.\n */\n function createNode() {\n let node = document.createElement('div');\n let content = document.createElement('ul');\n content.setAttribute('role', 'tablist');\n content.className = 'lm-TabBar-content';\n node.appendChild(content);\n let add = document.createElement('div');\n add.className = 'lm-TabBar-addButton lm-mod-hidden';\n add.setAttribute('tabindex', '-1');\n add.setAttribute('role', 'button');\n node.appendChild(add);\n return node;\n }\n Private.createNode = createNode;\n /**\n * Coerce a title or options into a real title.\n */\n function asTitle(value) {\n return value instanceof Title ? value : new Title(value);\n }\n Private.asTitle = asTitle;\n /**\n * Parse the transition duration for a tab node.\n */\n function parseTransitionDuration(tab) {\n let style = window.getComputedStyle(tab);\n return 1000 * (parseFloat(style.transitionDuration) || 0);\n }\n Private.parseTransitionDuration = parseTransitionDuration;\n /**\n * Get a snapshot of the current tab layout values.\n */\n function snapTabLayout(tabs, orientation) {\n let layout = new Array(tabs.length);\n for (let i = 0, n = tabs.length; i < n; ++i) {\n let node = tabs[i];\n let style = window.getComputedStyle(node);\n if (orientation === 'horizontal') {\n layout[i] = {\n pos: node.offsetLeft,\n size: node.offsetWidth,\n margin: parseFloat(style.marginLeft) || 0\n };\n }\n else {\n layout[i] = {\n pos: node.offsetTop,\n size: node.offsetHeight,\n margin: parseFloat(style.marginTop) || 0\n };\n }\n }\n return layout;\n }\n Private.snapTabLayout = snapTabLayout;\n /**\n * Test if the event exceeds the drag threshold.\n */\n function dragExceeded(data, event) {\n let dx = Math.abs(event.clientX - data.pressX);\n let dy = Math.abs(event.clientY - data.pressY);\n return dx >= Private.DRAG_THRESHOLD || dy >= Private.DRAG_THRESHOLD;\n }\n Private.dragExceeded = dragExceeded;\n /**\n * Test if the event exceeds the drag detach threshold.\n */\n function detachExceeded(data, event) {\n let rect = data.contentRect;\n return (event.clientX < rect.left - Private.DETACH_THRESHOLD ||\n event.clientX >= rect.right + Private.DETACH_THRESHOLD ||\n event.clientY < rect.top - Private.DETACH_THRESHOLD ||\n event.clientY >= rect.bottom + Private.DETACH_THRESHOLD);\n }\n Private.detachExceeded = detachExceeded;\n /**\n * Update the relative tab positions and computed target index.\n */\n function layoutTabs(tabs, data, event, orientation) {\n // Compute the orientation-sensitive values.\n let pressPos;\n let localPos;\n let clientPos;\n let clientSize;\n if (orientation === 'horizontal') {\n pressPos = data.pressX;\n localPos = event.clientX - data.contentRect.left;\n clientPos = event.clientX;\n clientSize = data.contentRect.width;\n }\n else {\n pressPos = data.pressY;\n localPos = event.clientY - data.contentRect.top;\n clientPos = event.clientY;\n clientSize = data.contentRect.height;\n }\n // Compute the target data.\n let targetIndex = data.index;\n let targetPos = localPos - data.tabPressPos;\n let targetEnd = targetPos + data.tabSize;\n // Update the relative tab positions.\n for (let i = 0, n = tabs.length; i < n; ++i) {\n let pxPos;\n let layout = data.tabLayout[i];\n let threshold = layout.pos + (layout.size >> 1);\n if (i < data.index && targetPos < threshold) {\n pxPos = `${data.tabSize + data.tabLayout[i + 1].margin}px`;\n targetIndex = Math.min(targetIndex, i);\n }\n else if (i > data.index && targetEnd > threshold) {\n pxPos = `${-data.tabSize - layout.margin}px`;\n targetIndex = Math.max(targetIndex, i);\n }\n else if (i === data.index) {\n let ideal = clientPos - pressPos;\n let limit = clientSize - (data.tabPos + data.tabSize);\n pxPos = `${Math.max(-data.tabPos, Math.min(ideal, limit))}px`;\n }\n else {\n pxPos = '';\n }\n if (orientation === 'horizontal') {\n tabs[i].style.left = pxPos;\n }\n else {\n tabs[i].style.top = pxPos;\n }\n }\n // Update the computed target index.\n data.targetIndex = targetIndex;\n }\n Private.layoutTabs = layoutTabs;\n /**\n * Position the drag tab at its final resting relative position.\n */\n function finalizeTabPosition(data, orientation) {\n // Compute the orientation-sensitive client size.\n let clientSize;\n if (orientation === 'horizontal') {\n clientSize = data.contentRect.width;\n }\n else {\n clientSize = data.contentRect.height;\n }\n // Compute the ideal final tab position.\n let ideal;\n if (data.targetIndex === data.index) {\n ideal = 0;\n }\n else if (data.targetIndex > data.index) {\n let tgt = data.tabLayout[data.targetIndex];\n ideal = tgt.pos + tgt.size - data.tabSize - data.tabPos;\n }\n else {\n let tgt = data.tabLayout[data.targetIndex];\n ideal = tgt.pos - data.tabPos;\n }\n // Compute the tab position limit.\n let limit = clientSize - (data.tabPos + data.tabSize);\n let final = Math.max(-data.tabPos, Math.min(ideal, limit));\n // Set the final orientation-sensitive position.\n if (orientation === 'horizontal') {\n data.tab.style.left = `${final}px`;\n }\n else {\n data.tab.style.top = `${final}px`;\n }\n }\n Private.finalizeTabPosition = finalizeTabPosition;\n /**\n * Reset the relative positions of the given tabs.\n */\n function resetTabPositions(tabs, orientation) {\n for (const tab of tabs) {\n if (orientation === 'horizontal') {\n tab.style.left = '';\n }\n else {\n tab.style.top = '';\n }\n }\n }\n Private.resetTabPositions = resetTabPositions;\n})(Private$7 || (Private$7 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which provides a flexible docking arrangement.\n *\n * #### Notes\n * The consumer of this layout is responsible for handling all signals\n * from the generated tab bars and managing the visibility of widgets\n * and tab bars as needed.\n */\nclass DockLayout extends Layout {\n /**\n * Construct a new dock layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options) {\n super();\n this._spacing = 4;\n this._dirty = false;\n this._root = null;\n this._box = null;\n this._items = new Map();\n this.renderer = options.renderer;\n if (options.spacing !== undefined) {\n this._spacing = Utils$1.clampDimension(options.spacing);\n }\n this._document = options.document || document;\n this._hiddenMode =\n options.hiddenMode !== undefined\n ? options.hiddenMode\n : Widget.HiddenMode.Display;\n }\n /**\n * Dispose of the resources held by the layout.\n *\n * #### Notes\n * This will clear and dispose all widgets in the layout.\n */\n dispose() {\n // Get an iterator over the widgets in the layout.\n let widgets = this[Symbol.iterator]();\n // Dispose of the layout items.\n this._items.forEach(item => {\n item.dispose();\n });\n // Clear the layout state before disposing the widgets.\n this._box = null;\n this._root = null;\n this._items.clear();\n // Dispose of the widgets contained in the old layout root.\n for (const widget of widgets) {\n widget.dispose();\n }\n // Dispose of the base class.\n super.dispose();\n }\n /**\n * The method for hiding child widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n get hiddenMode() {\n return this._hiddenMode;\n }\n set hiddenMode(v) {\n if (this._hiddenMode === v) {\n return;\n }\n this._hiddenMode = v;\n for (const bar of this.tabBars()) {\n if (bar.titles.length > 1) {\n for (const title of bar.titles) {\n title.owner.hiddenMode = this._hiddenMode;\n }\n }\n }\n }\n /**\n * Get the inter-element spacing for the dock layout.\n */\n get spacing() {\n return this._spacing;\n }\n /**\n * Set the inter-element spacing for the dock layout.\n */\n set spacing(value) {\n value = Utils$1.clampDimension(value);\n if (this._spacing === value) {\n return;\n }\n this._spacing = value;\n if (!this.parent) {\n return;\n }\n this.parent.fit();\n }\n /**\n * Whether the dock layout is empty.\n */\n get isEmpty() {\n return this._root === null;\n }\n /**\n * Create an iterator over all widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n *\n * #### Notes\n * This iterator includes the generated tab bars.\n */\n [Symbol.iterator]() {\n return this._root ? this._root.iterAllWidgets() : empty();\n }\n /**\n * Create an iterator over the user widgets in the layout.\n *\n * @returns A new iterator over the user widgets in the layout.\n *\n * #### Notes\n * This iterator does not include the generated tab bars.\n */\n widgets() {\n return this._root ? this._root.iterUserWidgets() : empty();\n }\n /**\n * Create an iterator over the selected widgets in the layout.\n *\n * @returns A new iterator over the selected user widgets.\n *\n * #### Notes\n * This iterator yields the widgets corresponding to the current tab\n * of each tab bar in the layout.\n */\n selectedWidgets() {\n return this._root ? this._root.iterSelectedWidgets() : empty();\n }\n /**\n * Create an iterator over the tab bars in the layout.\n *\n * @returns A new iterator over the tab bars in the layout.\n *\n * #### Notes\n * This iterator does not include the user widgets.\n */\n tabBars() {\n return this._root ? this._root.iterTabBars() : empty();\n }\n /**\n * Create an iterator over the handles in the layout.\n *\n * @returns A new iterator over the handles in the layout.\n */\n handles() {\n return this._root ? this._root.iterHandles() : empty();\n }\n /**\n * Move a handle to the given offset position.\n *\n * @param handle - The handle to move.\n *\n * @param offsetX - The desired offset X position of the handle.\n *\n * @param offsetY - The desired offset Y position of the handle.\n *\n * #### Notes\n * If the given handle is not contained in the layout, this is no-op.\n *\n * The handle will be moved as close as possible to the desired\n * position without violating any of the layout constraints.\n *\n * Only one of the coordinates is used depending on the orientation\n * of the handle. This method accepts both coordinates to make it\n * easy to invoke from a mouse move event without needing to know\n * the handle orientation.\n */\n moveHandle(handle, offsetX, offsetY) {\n // Bail early if there is no root or if the handle is hidden.\n let hidden = handle.classList.contains('lm-mod-hidden');\n if (!this._root || hidden) {\n return;\n }\n // Lookup the split node for the handle.\n let data = this._root.findSplitNode(handle);\n if (!data) {\n return;\n }\n // Compute the desired delta movement for the handle.\n let delta;\n if (data.node.orientation === 'horizontal') {\n delta = offsetX - handle.offsetLeft;\n }\n else {\n delta = offsetY - handle.offsetTop;\n }\n // Bail if there is no handle movement.\n if (delta === 0) {\n return;\n }\n // Prevent sibling resizing unless needed.\n data.node.holdSizes();\n // Adjust the sizers to reflect the handle movement.\n BoxEngine.adjust(data.node.sizers, data.index, delta);\n // Update the layout of the widgets.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Save the current configuration of the dock layout.\n *\n * @returns A new config object for the current layout state.\n *\n * #### Notes\n * The return value can be provided to the `restoreLayout` method\n * in order to restore the layout to its current configuration.\n */\n saveLayout() {\n // Bail early if there is no root.\n if (!this._root) {\n return { main: null };\n }\n // Hold the current sizes in the layout tree.\n this._root.holdAllSizes();\n // Return the layout config.\n return { main: this._root.createConfig() };\n }\n /**\n * Restore the layout to a previously saved configuration.\n *\n * @param config - The layout configuration to restore.\n *\n * #### Notes\n * Widgets which currently belong to the layout but which are not\n * contained in the config will be unparented.\n */\n restoreLayout(config) {\n // Create the widget set for validating the config.\n let widgetSet = new Set();\n // Normalize the main area config and collect the widgets.\n let mainConfig;\n if (config.main) {\n mainConfig = Private$6.normalizeAreaConfig(config.main, widgetSet);\n }\n else {\n mainConfig = null;\n }\n // Create iterators over the old content.\n let oldWidgets = this.widgets();\n let oldTabBars = this.tabBars();\n let oldHandles = this.handles();\n // Clear the root before removing the old content.\n this._root = null;\n // Unparent the old widgets which are not in the new config.\n for (const widget of oldWidgets) {\n if (!widgetSet.has(widget)) {\n widget.parent = null;\n }\n }\n // Dispose of the old tab bars.\n for (const tabBar of oldTabBars) {\n tabBar.dispose();\n }\n // Remove the old handles.\n for (const handle of oldHandles) {\n if (handle.parentNode) {\n handle.parentNode.removeChild(handle);\n }\n }\n // Reparent the new widgets to the current parent.\n for (const widget of widgetSet) {\n widget.parent = this.parent;\n }\n // Create the root node for the new config.\n if (mainConfig) {\n this._root = Private$6.realizeAreaConfig(mainConfig, {\n // Ignoring optional `document` argument as we must reuse `this._document`\n createTabBar: (document) => this._createTabBar(),\n createHandle: () => this._createHandle()\n }, this._document);\n }\n else {\n this._root = null;\n }\n // If there is no parent, there is nothing more to do.\n if (!this.parent) {\n return;\n }\n // Attach the new widgets to the parent.\n widgetSet.forEach(widget => {\n this.attachWidget(widget);\n });\n // Post a fit request to the parent.\n this.parent.fit();\n }\n /**\n * Add a widget to the dock layout.\n *\n * @param widget - The widget to add to the dock layout.\n *\n * @param options - The additional options for adding the widget.\n *\n * #### Notes\n * The widget will be moved if it is already contained in the layout.\n *\n * An error will be thrown if the reference widget is invalid.\n */\n addWidget(widget, options = {}) {\n // Parse the options.\n let ref = options.ref || null;\n let mode = options.mode || 'tab-after';\n // Find the tab node which holds the reference widget.\n let refNode = null;\n if (this._root && ref) {\n refNode = this._root.findTabNode(ref);\n }\n // Throw an error if the reference widget is invalid.\n if (ref && !refNode) {\n throw new Error('Reference widget is not in the layout.');\n }\n // Reparent the widget to the current layout parent.\n widget.parent = this.parent;\n // Insert the widget according to the insert mode.\n switch (mode) {\n case 'tab-after':\n this._insertTab(widget, ref, refNode, true);\n break;\n case 'tab-before':\n this._insertTab(widget, ref, refNode, false);\n break;\n case 'split-top':\n this._insertSplit(widget, ref, refNode, 'vertical', false);\n break;\n case 'split-left':\n this._insertSplit(widget, ref, refNode, 'horizontal', false);\n break;\n case 'split-right':\n this._insertSplit(widget, ref, refNode, 'horizontal', true);\n break;\n case 'split-bottom':\n this._insertSplit(widget, ref, refNode, 'vertical', true);\n break;\n case 'merge-top':\n this._insertSplit(widget, ref, refNode, 'vertical', false, true);\n break;\n case 'merge-left':\n this._insertSplit(widget, ref, refNode, 'horizontal', false, true);\n break;\n case 'merge-right':\n this._insertSplit(widget, ref, refNode, 'horizontal', true, true);\n break;\n case 'merge-bottom':\n this._insertSplit(widget, ref, refNode, 'vertical', true, true);\n break;\n }\n // Do nothing else if there is no parent widget.\n if (!this.parent) {\n return;\n }\n // Ensure the widget is attached to the parent widget.\n this.attachWidget(widget);\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Remove a widget from the layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n // Remove the widget from its current layout location.\n this._removeWidget(widget);\n // Do nothing else if there is no parent widget.\n if (!this.parent) {\n return;\n }\n // Detach the widget from the parent widget.\n this.detachWidget(widget);\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Find the tab area which contains the given client position.\n *\n * @param clientX - The client X position of interest.\n *\n * @param clientY - The client Y position of interest.\n *\n * @returns The geometry of the tab area at the given position, or\n * `null` if there is no tab area at the given position.\n */\n hitTestTabAreas(clientX, clientY) {\n // Bail early if hit testing cannot produce valid results.\n if (!this._root || !this.parent || !this.parent.isVisible) {\n return null;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Convert from client to local coordinates.\n let rect = this.parent.node.getBoundingClientRect();\n let x = clientX - rect.left - this._box.borderLeft;\n let y = clientY - rect.top - this._box.borderTop;\n // Find the tab layout node at the local position.\n let tabNode = this._root.hitTestTabNodes(x, y);\n // Bail if a tab layout node was not found.\n if (!tabNode) {\n return null;\n }\n // Extract the data from the tab node.\n let { tabBar, top, left, width, height } = tabNode;\n // Compute the right and bottom edges of the tab area.\n let borderWidth = this._box.borderLeft + this._box.borderRight;\n let borderHeight = this._box.borderTop + this._box.borderBottom;\n let right = rect.width - borderWidth - (left + width);\n let bottom = rect.height - borderHeight - (top + height);\n // Return the hit test results.\n return { tabBar, x, y, top, left, right, bottom, width, height };\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n // Perform superclass initialization.\n super.init();\n // Attach each widget to the parent.\n for (const widget of this) {\n this.attachWidget(widget);\n }\n // Attach each handle to the parent.\n for (const handle of this.handles()) {\n this.parent.node.appendChild(handle);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Attach the widget to the layout parent widget.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a no-op if the widget is already attached.\n */\n attachWidget(widget) {\n // Do nothing if the widget is already attached.\n if (this.parent.node === widget.node.parentNode) {\n return;\n }\n // Create the layout item for the widget.\n this._items.set(widget, new LayoutItem(widget));\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Detach the widget from the layout parent widget.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a no-op if the widget is not attached.\n */\n detachWidget(widget) {\n // Do nothing if the widget is not attached.\n if (this.parent.node !== widget.node.parentNode) {\n return;\n }\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Delete the layout item for the widget.\n let item = this._items.get(widget);\n if (item) {\n this._items.delete(widget);\n item.dispose();\n }\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Remove the specified widget from the layout structure.\n *\n * #### Notes\n * This is a no-op if the widget is not in the layout tree.\n *\n * This does not detach the widget from the parent node.\n */\n _removeWidget(widget) {\n // Bail early if there is no layout root.\n if (!this._root) {\n return;\n }\n // Find the tab node which contains the given widget.\n let tabNode = this._root.findTabNode(widget);\n // Bail early if the tab node is not found.\n if (!tabNode) {\n return;\n }\n Private$6.removeAria(widget);\n // If there are multiple tabs, just remove the widget's tab.\n if (tabNode.tabBar.titles.length > 1) {\n tabNode.tabBar.removeTab(widget.title);\n if (this._hiddenMode === Widget.HiddenMode.Scale &&\n tabNode.tabBar.titles.length == 1) {\n const existingWidget = tabNode.tabBar.titles[0].owner;\n existingWidget.hiddenMode = Widget.HiddenMode.Display;\n }\n return;\n }\n // Otherwise, the tab node needs to be removed...\n // Dispose the tab bar.\n tabNode.tabBar.dispose();\n // Handle the case where the tab node is the root.\n if (this._root === tabNode) {\n this._root = null;\n return;\n }\n // Otherwise, remove the tab node from its parent...\n // Prevent widget resizing unless needed.\n this._root.holdAllSizes();\n // Clear the parent reference on the tab node.\n let splitNode = tabNode.parent;\n tabNode.parent = null;\n // Remove the tab node from its parent split node.\n let i = ArrayExt.removeFirstOf(splitNode.children, tabNode);\n let handle = ArrayExt.removeAt(splitNode.handles, i);\n ArrayExt.removeAt(splitNode.sizers, i);\n // Remove the handle from its parent DOM node.\n if (handle.parentNode) {\n handle.parentNode.removeChild(handle);\n }\n // If there are multiple children, just update the handles.\n if (splitNode.children.length > 1) {\n splitNode.syncHandles();\n return;\n }\n // Otherwise, the split node also needs to be removed...\n // Clear the parent reference on the split node.\n let maybeParent = splitNode.parent;\n splitNode.parent = null;\n // Lookup the remaining child node and handle.\n let childNode = splitNode.children[0];\n let childHandle = splitNode.handles[0];\n // Clear the split node data.\n splitNode.children.length = 0;\n splitNode.handles.length = 0;\n splitNode.sizers.length = 0;\n // Remove the child handle from its parent node.\n if (childHandle.parentNode) {\n childHandle.parentNode.removeChild(childHandle);\n }\n // Handle the case where the split node is the root.\n if (this._root === splitNode) {\n childNode.parent = null;\n this._root = childNode;\n return;\n }\n // Otherwise, move the child node to the parent node...\n let parentNode = maybeParent;\n // Lookup the index of the split node.\n let j = parentNode.children.indexOf(splitNode);\n // Handle the case where the child node is a tab node.\n if (childNode instanceof Private$6.TabLayoutNode) {\n childNode.parent = parentNode;\n parentNode.children[j] = childNode;\n return;\n }\n // Remove the split data from the parent.\n let splitHandle = ArrayExt.removeAt(parentNode.handles, j);\n ArrayExt.removeAt(parentNode.children, j);\n ArrayExt.removeAt(parentNode.sizers, j);\n // Remove the handle from its parent node.\n if (splitHandle.parentNode) {\n splitHandle.parentNode.removeChild(splitHandle);\n }\n // The child node and the split parent node will have the same\n // orientation. Merge the grand-children with the parent node.\n for (let i = 0, n = childNode.children.length; i < n; ++i) {\n let gChild = childNode.children[i];\n let gHandle = childNode.handles[i];\n let gSizer = childNode.sizers[i];\n ArrayExt.insert(parentNode.children, j + i, gChild);\n ArrayExt.insert(parentNode.handles, j + i, gHandle);\n ArrayExt.insert(parentNode.sizers, j + i, gSizer);\n gChild.parent = parentNode;\n }\n // Clear the child node.\n childNode.children.length = 0;\n childNode.handles.length = 0;\n childNode.sizers.length = 0;\n childNode.parent = null;\n // Sync the handles on the parent node.\n parentNode.syncHandles();\n }\n /**\n * Create the tab layout node to hold the widget.\n */\n _createTabNode(widget) {\n let tabNode = new Private$6.TabLayoutNode(this._createTabBar());\n tabNode.tabBar.addTab(widget.title);\n Private$6.addAria(widget, tabNode.tabBar);\n return tabNode;\n }\n /**\n * Insert a widget next to an existing tab.\n *\n * #### Notes\n * This does not attach the widget to the parent widget.\n */\n _insertTab(widget, ref, refNode, after) {\n // Do nothing if the tab is inserted next to itself.\n if (widget === ref) {\n return;\n }\n // Create the root if it does not exist.\n if (!this._root) {\n let tabNode = new Private$6.TabLayoutNode(this._createTabBar());\n tabNode.tabBar.addTab(widget.title);\n this._root = tabNode;\n Private$6.addAria(widget, tabNode.tabBar);\n return;\n }\n // Use the first tab node as the ref node if needed.\n if (!refNode) {\n refNode = this._root.findFirstTabNode();\n }\n // If the widget is not contained in the ref node, ensure it is\n // removed from the layout and hidden before being added again.\n if (refNode.tabBar.titles.indexOf(widget.title) === -1) {\n this._removeWidget(widget);\n widget.hide();\n }\n // Lookup the target index for inserting the tab.\n let index;\n if (ref) {\n index = refNode.tabBar.titles.indexOf(ref.title);\n }\n else {\n index = refNode.tabBar.currentIndex;\n }\n // Using transform create an additional layer in the pixel pipeline\n // to limit the number of layer, it is set only if there is more than one widget.\n if (this._hiddenMode === Widget.HiddenMode.Scale) {\n if (refNode.tabBar.titles.length === 0) {\n // Singular tab should use display mode to limit number of layers.\n widget.hiddenMode = Widget.HiddenMode.Display;\n }\n else if (refNode.tabBar.titles.length == 1) {\n // If we are adding a second tab, switch the existing tab back to scale.\n const existingWidget = refNode.tabBar.titles[0].owner;\n existingWidget.hiddenMode = Widget.HiddenMode.Scale;\n }\n else {\n // For the third and subsequent tabs no special action is needed.\n widget.hiddenMode = Widget.HiddenMode.Scale;\n }\n }\n else {\n // For all other modes just propagate the current mode.\n widget.hiddenMode = this._hiddenMode;\n }\n // Insert the widget's tab relative to the target index.\n refNode.tabBar.insertTab(index + (after ? 1 : 0), widget.title);\n Private$6.addAria(widget, refNode.tabBar);\n }\n /**\n * Insert a widget as a new split area.\n *\n * #### Notes\n * This does not attach the widget to the parent widget.\n */\n _insertSplit(widget, ref, refNode, orientation, after, merge = false) {\n // Do nothing if there is no effective split.\n if (widget === ref && refNode && refNode.tabBar.titles.length === 1) {\n return;\n }\n // Ensure the widget is removed from the current layout.\n this._removeWidget(widget);\n // Set the root if it does not exist.\n if (!this._root) {\n this._root = this._createTabNode(widget);\n return;\n }\n // If the ref node parent is null, split the root.\n if (!refNode || !refNode.parent) {\n // Ensure the root is split with the correct orientation.\n let root = this._splitRoot(orientation);\n // Determine the insert index for the new tab node.\n let i = after ? root.children.length : 0;\n // Normalize the split node.\n root.normalizeSizes();\n // Create the sizer for new tab node.\n let sizer = Private$6.createSizer(refNode ? 1 : Private$6.GOLDEN_RATIO);\n // Insert the tab node sized to the golden ratio.\n let tabNode = this._createTabNode(widget);\n ArrayExt.insert(root.children, i, tabNode);\n ArrayExt.insert(root.sizers, i, sizer);\n ArrayExt.insert(root.handles, i, this._createHandle());\n tabNode.parent = root;\n // Re-normalize the split node to maintain the ratios.\n root.normalizeSizes();\n // Finally, synchronize the visibility of the handles.\n root.syncHandles();\n return;\n }\n // Lookup the split node for the ref widget.\n let splitNode = refNode.parent;\n // If the split node already had the correct orientation,\n // the widget can be inserted into the split node directly.\n if (splitNode.orientation === orientation) {\n // Find the index of the ref node.\n let i = splitNode.children.indexOf(refNode);\n // Conditionally reuse a tab layout found in the wanted position.\n if (merge) {\n let j = i + (after ? 1 : -1);\n let sibling = splitNode.children[j];\n if (sibling instanceof Private$6.TabLayoutNode) {\n this._insertTab(widget, null, sibling, true);\n ++sibling.tabBar.currentIndex;\n return;\n }\n }\n // Normalize the split node.\n splitNode.normalizeSizes();\n // Consume half the space for the insert location.\n let s = (splitNode.sizers[i].sizeHint /= 2);\n // Insert the tab node sized to the other half.\n let j = i + (after ? 1 : 0);\n let tabNode = this._createTabNode(widget);\n ArrayExt.insert(splitNode.children, j, tabNode);\n ArrayExt.insert(splitNode.sizers, j, Private$6.createSizer(s));\n ArrayExt.insert(splitNode.handles, j, this._createHandle());\n tabNode.parent = splitNode;\n // Finally, synchronize the visibility of the handles.\n splitNode.syncHandles();\n return;\n }\n // Remove the ref node from the split node.\n let i = ArrayExt.removeFirstOf(splitNode.children, refNode);\n // Create a new normalized split node for the children.\n let childNode = new Private$6.SplitLayoutNode(orientation);\n childNode.normalized = true;\n // Add the ref node sized to half the space.\n childNode.children.push(refNode);\n childNode.sizers.push(Private$6.createSizer(0.5));\n childNode.handles.push(this._createHandle());\n refNode.parent = childNode;\n // Add the tab node sized to the other half.\n let j = after ? 1 : 0;\n let tabNode = this._createTabNode(widget);\n ArrayExt.insert(childNode.children, j, tabNode);\n ArrayExt.insert(childNode.sizers, j, Private$6.createSizer(0.5));\n ArrayExt.insert(childNode.handles, j, this._createHandle());\n tabNode.parent = childNode;\n // Synchronize the visibility of the handles.\n childNode.syncHandles();\n // Finally, add the new child node to the original split node.\n ArrayExt.insert(splitNode.children, i, childNode);\n childNode.parent = splitNode;\n }\n /**\n * Ensure the root is a split node with the given orientation.\n */\n _splitRoot(orientation) {\n // Bail early if the root already meets the requirements.\n let oldRoot = this._root;\n if (oldRoot instanceof Private$6.SplitLayoutNode) {\n if (oldRoot.orientation === orientation) {\n return oldRoot;\n }\n }\n // Create a new root node with the specified orientation.\n let newRoot = (this._root = new Private$6.SplitLayoutNode(orientation));\n // Add the old root to the new root.\n if (oldRoot) {\n newRoot.children.push(oldRoot);\n newRoot.sizers.push(Private$6.createSizer(0));\n newRoot.handles.push(this._createHandle());\n oldRoot.parent = newRoot;\n }\n // Return the new root as a convenience.\n return newRoot;\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Set up the computed minimum size.\n let minW = 0;\n let minH = 0;\n // Update the size limits for the layout tree.\n if (this._root) {\n let limits = this._root.fit(this._spacing, this._items);\n minW = limits.minWidth;\n minH = limits.minHeight;\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Bail early if there is no root layout node.\n if (!this._root) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the actual layout bounds adjusted for border and padding.\n let x = this._box.paddingTop;\n let y = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Update the geometry of the layout tree.\n this._root.update(x, y, width, height, this._spacing, this._items);\n }\n /**\n * Create a new tab bar for use by the dock layout.\n *\n * #### Notes\n * The tab bar will be attached to the parent if it exists.\n */\n _createTabBar() {\n // Create the tab bar using the renderer.\n let tabBar = this.renderer.createTabBar(this._document);\n // Enforce necessary tab bar behavior.\n tabBar.orientation = 'horizontal';\n // Attach the tab bar to the parent if possible.\n if (this.parent) {\n this.attachWidget(tabBar);\n }\n // Return the initialized tab bar.\n return tabBar;\n }\n /**\n * Create a new handle for the dock layout.\n *\n * #### Notes\n * The handle will be attached to the parent if it exists.\n */\n _createHandle() {\n // Create the handle using the renderer.\n let handle = this.renderer.createHandle();\n // Initialize the handle layout behavior.\n let style = handle.style;\n style.position = 'absolute';\n style.contain = 'strict';\n style.top = '0';\n style.left = '0';\n style.width = '0';\n style.height = '0';\n // Attach the handle to the parent if it exists.\n if (this.parent) {\n this.parent.node.appendChild(handle);\n }\n // Return the initialized handle.\n return handle;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$6;\n(function (Private) {\n /**\n * A fraction used for sizing root panels; ~= `1 / golden_ratio`.\n */\n Private.GOLDEN_RATIO = 0.618;\n /**\n * Create a box sizer with an initial size hint.\n */\n function createSizer(hint) {\n let sizer = new BoxSizer();\n sizer.sizeHint = hint;\n sizer.size = hint;\n return sizer;\n }\n Private.createSizer = createSizer;\n /**\n * Normalize an area config object and collect the visited widgets.\n */\n function normalizeAreaConfig(config, widgetSet) {\n let result;\n if (config.type === 'tab-area') {\n result = normalizeTabAreaConfig(config, widgetSet);\n }\n else {\n result = normalizeSplitAreaConfig(config, widgetSet);\n }\n return result;\n }\n Private.normalizeAreaConfig = normalizeAreaConfig;\n /**\n * Convert a normalized area config into a layout tree.\n */\n function realizeAreaConfig(config, renderer, document) {\n let node;\n if (config.type === 'tab-area') {\n node = realizeTabAreaConfig(config, renderer, document);\n }\n else {\n node = realizeSplitAreaConfig(config, renderer, document);\n }\n return node;\n }\n Private.realizeAreaConfig = realizeAreaConfig;\n /**\n * A layout node which holds the data for a tabbed area.\n */\n class TabLayoutNode {\n /**\n * Construct a new tab layout node.\n *\n * @param tabBar - The tab bar to use for the layout node.\n */\n constructor(tabBar) {\n /**\n * The parent of the layout node.\n */\n this.parent = null;\n this._top = 0;\n this._left = 0;\n this._width = 0;\n this._height = 0;\n let tabSizer = new BoxSizer();\n let widgetSizer = new BoxSizer();\n tabSizer.stretch = 0;\n widgetSizer.stretch = 1;\n this.tabBar = tabBar;\n this.sizers = [tabSizer, widgetSizer];\n }\n /**\n * The most recent value for the `top` edge of the layout box.\n */\n get top() {\n return this._top;\n }\n /**\n * The most recent value for the `left` edge of the layout box.\n */\n get left() {\n return this._left;\n }\n /**\n * The most recent value for the `width` of the layout box.\n */\n get width() {\n return this._width;\n }\n /**\n * The most recent value for the `height` of the layout box.\n */\n get height() {\n return this._height;\n }\n /**\n * Create an iterator for all widgets in the layout tree.\n */\n *iterAllWidgets() {\n yield this.tabBar;\n yield* this.iterUserWidgets();\n }\n /**\n * Create an iterator for the user widgets in the layout tree.\n */\n *iterUserWidgets() {\n for (const title of this.tabBar.titles) {\n yield title.owner;\n }\n }\n /**\n * Create an iterator for the selected widgets in the layout tree.\n */\n *iterSelectedWidgets() {\n let title = this.tabBar.currentTitle;\n if (title) {\n yield title.owner;\n }\n }\n /**\n * Create an iterator for the tab bars in the layout tree.\n */\n *iterTabBars() {\n yield this.tabBar;\n }\n /**\n * Create an iterator for the handles in the layout tree.\n */\n // eslint-disable-next-line require-yield\n *iterHandles() {\n return;\n }\n /**\n * Find the tab layout node which contains the given widget.\n */\n findTabNode(widget) {\n return this.tabBar.titles.indexOf(widget.title) !== -1 ? this : null;\n }\n /**\n * Find the split layout node which contains the given handle.\n */\n findSplitNode(handle) {\n return null;\n }\n /**\n * Find the first tab layout node in a layout tree.\n */\n findFirstTabNode() {\n return this;\n }\n /**\n * Find the tab layout node which contains the local point.\n */\n hitTestTabNodes(x, y) {\n if (x < this._left || x >= this._left + this._width) {\n return null;\n }\n if (y < this._top || y >= this._top + this._height) {\n return null;\n }\n return this;\n }\n /**\n * Create a configuration object for the layout tree.\n */\n createConfig() {\n let widgets = this.tabBar.titles.map(title => title.owner);\n let currentIndex = this.tabBar.currentIndex;\n return { type: 'tab-area', widgets, currentIndex };\n }\n /**\n * Recursively hold all of the sizes in the layout tree.\n *\n * This ignores the sizers of tab layout nodes.\n */\n holdAllSizes() {\n return;\n }\n /**\n * Fit the layout tree.\n */\n fit(spacing, items) {\n // Set up the limit variables.\n let minWidth = 0;\n let minHeight = 0;\n let maxWidth = Infinity;\n let maxHeight = Infinity;\n // Lookup the tab bar layout item.\n let tabBarItem = items.get(this.tabBar);\n // Lookup the widget layout item.\n let current = this.tabBar.currentTitle;\n let widgetItem = current ? items.get(current.owner) : undefined;\n // Lookup the tab bar and widget sizers.\n let [tabBarSizer, widgetSizer] = this.sizers;\n // Update the tab bar limits.\n if (tabBarItem) {\n tabBarItem.fit();\n }\n // Update the widget limits.\n if (widgetItem) {\n widgetItem.fit();\n }\n // Update the results and sizer for the tab bar.\n if (tabBarItem && !tabBarItem.isHidden) {\n minWidth = Math.max(minWidth, tabBarItem.minWidth);\n minHeight += tabBarItem.minHeight;\n tabBarSizer.minSize = tabBarItem.minHeight;\n tabBarSizer.maxSize = tabBarItem.maxHeight;\n }\n else {\n tabBarSizer.minSize = 0;\n tabBarSizer.maxSize = 0;\n }\n // Update the results and sizer for the current widget.\n if (widgetItem && !widgetItem.isHidden) {\n minWidth = Math.max(minWidth, widgetItem.minWidth);\n minHeight += widgetItem.minHeight;\n widgetSizer.minSize = widgetItem.minHeight;\n widgetSizer.maxSize = Infinity;\n }\n else {\n widgetSizer.minSize = 0;\n widgetSizer.maxSize = Infinity;\n }\n // Return the computed size limits for the layout node.\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n /**\n * Update the layout tree.\n */\n update(left, top, width, height, spacing, items) {\n // Update the layout box values.\n this._top = top;\n this._left = left;\n this._width = width;\n this._height = height;\n // Lookup the tab bar layout item.\n let tabBarItem = items.get(this.tabBar);\n // Lookup the widget layout item.\n let current = this.tabBar.currentTitle;\n let widgetItem = current ? items.get(current.owner) : undefined;\n // Distribute the layout space to the sizers.\n BoxEngine.calc(this.sizers, height);\n // Update the tab bar item using the computed size.\n if (tabBarItem && !tabBarItem.isHidden) {\n let size = this.sizers[0].size;\n tabBarItem.update(left, top, width, size);\n top += size;\n }\n // Layout the widget using the computed size.\n if (widgetItem && !widgetItem.isHidden) {\n let size = this.sizers[1].size;\n widgetItem.update(left, top, width, size);\n }\n }\n }\n Private.TabLayoutNode = TabLayoutNode;\n /**\n * A layout node which holds the data for a split area.\n */\n class SplitLayoutNode {\n /**\n * Construct a new split layout node.\n *\n * @param orientation - The orientation of the node.\n */\n constructor(orientation) {\n /**\n * The parent of the layout node.\n */\n this.parent = null;\n /**\n * Whether the sizers have been normalized.\n */\n this.normalized = false;\n /**\n * The child nodes for the split node.\n */\n this.children = [];\n /**\n * The box sizers for the layout children.\n */\n this.sizers = [];\n /**\n * The handles for the layout children.\n */\n this.handles = [];\n this.orientation = orientation;\n }\n /**\n * Create an iterator for all widgets in the layout tree.\n */\n *iterAllWidgets() {\n for (const child of this.children) {\n yield* child.iterAllWidgets();\n }\n }\n /**\n * Create an iterator for the user widgets in the layout tree.\n */\n *iterUserWidgets() {\n for (const child of this.children) {\n yield* child.iterUserWidgets();\n }\n }\n /**\n * Create an iterator for the selected widgets in the layout tree.\n */\n *iterSelectedWidgets() {\n for (const child of this.children) {\n yield* child.iterSelectedWidgets();\n }\n }\n /**\n * Create an iterator for the tab bars in the layout tree.\n */\n *iterTabBars() {\n for (const child of this.children) {\n yield* child.iterTabBars();\n }\n }\n /**\n * Create an iterator for the handles in the layout tree.\n */\n *iterHandles() {\n yield* this.handles;\n for (const child of this.children) {\n yield* child.iterHandles();\n }\n }\n /**\n * Find the tab layout node which contains the given widget.\n */\n findTabNode(widget) {\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let result = this.children[i].findTabNode(widget);\n if (result) {\n return result;\n }\n }\n return null;\n }\n /**\n * Find the split layout node which contains the given handle.\n */\n findSplitNode(handle) {\n let index = this.handles.indexOf(handle);\n if (index !== -1) {\n return { index, node: this };\n }\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let result = this.children[i].findSplitNode(handle);\n if (result) {\n return result;\n }\n }\n return null;\n }\n /**\n * Find the first tab layout node in a layout tree.\n */\n findFirstTabNode() {\n if (this.children.length === 0) {\n return null;\n }\n return this.children[0].findFirstTabNode();\n }\n /**\n * Find the tab layout node which contains the local point.\n */\n hitTestTabNodes(x, y) {\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let result = this.children[i].hitTestTabNodes(x, y);\n if (result) {\n return result;\n }\n }\n return null;\n }\n /**\n * Create a configuration object for the layout tree.\n */\n createConfig() {\n let orientation = this.orientation;\n let sizes = this.createNormalizedSizes();\n let children = this.children.map(child => child.createConfig());\n return { type: 'split-area', orientation, children, sizes };\n }\n /**\n * Sync the visibility and orientation of the handles.\n */\n syncHandles() {\n this.handles.forEach((handle, i) => {\n handle.setAttribute('data-orientation', this.orientation);\n if (i === this.handles.length - 1) {\n handle.classList.add('lm-mod-hidden');\n }\n else {\n handle.classList.remove('lm-mod-hidden');\n }\n });\n }\n /**\n * Hold the current sizes of the box sizers.\n *\n * This sets the size hint of each sizer to its current size.\n */\n holdSizes() {\n for (const sizer of this.sizers) {\n sizer.sizeHint = sizer.size;\n }\n }\n /**\n * Recursively hold all of the sizes in the layout tree.\n *\n * This ignores the sizers of tab layout nodes.\n */\n holdAllSizes() {\n for (const child of this.children) {\n child.holdAllSizes();\n }\n this.holdSizes();\n }\n /**\n * Normalize the sizes of the split layout node.\n */\n normalizeSizes() {\n // Bail early if the sizers are empty.\n let n = this.sizers.length;\n if (n === 0) {\n return;\n }\n // Hold the current sizes of the sizers.\n this.holdSizes();\n // Compute the sum of the sizes.\n let sum = this.sizers.reduce((v, sizer) => v + sizer.sizeHint, 0);\n // Normalize the sizes based on the sum.\n if (sum === 0) {\n for (const sizer of this.sizers) {\n sizer.size = sizer.sizeHint = 1 / n;\n }\n }\n else {\n for (const sizer of this.sizers) {\n sizer.size = sizer.sizeHint /= sum;\n }\n }\n // Mark the sizes as normalized.\n this.normalized = true;\n }\n /**\n * Snap the normalized sizes of the split layout node.\n */\n createNormalizedSizes() {\n // Bail early if the sizers are empty.\n let n = this.sizers.length;\n if (n === 0) {\n return [];\n }\n // Grab the current sizes of the sizers.\n let sizes = this.sizers.map(sizer => sizer.size);\n // Compute the sum of the sizes.\n let sum = sizes.reduce((v, size) => v + size, 0);\n // Normalize the sizes based on the sum.\n if (sum === 0) {\n for (let i = sizes.length - 1; i > -1; i--) {\n sizes[i] = 1 / n;\n }\n }\n else {\n for (let i = sizes.length - 1; i > -1; i--) {\n sizes[i] /= sum;\n }\n }\n // Return the normalized sizes.\n return sizes;\n }\n /**\n * Fit the layout tree.\n */\n fit(spacing, items) {\n // Compute the required fixed space.\n let horizontal = this.orientation === 'horizontal';\n let fixed = Math.max(0, this.children.length - 1) * spacing;\n // Set up the limit variables.\n let minWidth = horizontal ? fixed : 0;\n let minHeight = horizontal ? 0 : fixed;\n let maxWidth = Infinity;\n let maxHeight = Infinity;\n // Fit the children and update the limits.\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let limits = this.children[i].fit(spacing, items);\n if (horizontal) {\n minHeight = Math.max(minHeight, limits.minHeight);\n minWidth += limits.minWidth;\n this.sizers[i].minSize = limits.minWidth;\n }\n else {\n minWidth = Math.max(minWidth, limits.minWidth);\n minHeight += limits.minHeight;\n this.sizers[i].minSize = limits.minHeight;\n }\n }\n // Return the computed limits for the layout node.\n return { minWidth, minHeight, maxWidth, maxHeight };\n }\n /**\n * Update the layout tree.\n */\n update(left, top, width, height, spacing, items) {\n // Compute the available layout space.\n let horizontal = this.orientation === 'horizontal';\n let fixed = Math.max(0, this.children.length - 1) * spacing;\n let space = Math.max(0, (horizontal ? width : height) - fixed);\n // De-normalize the sizes if needed.\n if (this.normalized) {\n for (const sizer of this.sizers) {\n sizer.sizeHint *= space;\n }\n this.normalized = false;\n }\n // Distribute the layout space to the sizers.\n BoxEngine.calc(this.sizers, space);\n // Update the geometry of the child nodes and handles.\n for (let i = 0, n = this.children.length; i < n; ++i) {\n let child = this.children[i];\n let size = this.sizers[i].size;\n let handleStyle = this.handles[i].style;\n if (horizontal) {\n child.update(left, top, size, height, spacing, items);\n left += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${spacing}px`;\n handleStyle.height = `${height}px`;\n left += spacing;\n }\n else {\n child.update(left, top, width, size, spacing, items);\n top += size;\n handleStyle.top = `${top}px`;\n handleStyle.left = `${left}px`;\n handleStyle.width = `${width}px`;\n handleStyle.height = `${spacing}px`;\n top += spacing;\n }\n }\n }\n }\n Private.SplitLayoutNode = SplitLayoutNode;\n function addAria(widget, tabBar) {\n widget.node.setAttribute('role', 'tabpanel');\n let renderer = tabBar.renderer;\n if (renderer instanceof TabBar.Renderer) {\n let tabId = renderer.createTabKey({\n title: widget.title,\n current: false,\n zIndex: 0\n });\n widget.node.setAttribute('aria-labelledby', tabId);\n }\n }\n Private.addAria = addAria;\n function removeAria(widget) {\n widget.node.removeAttribute('role');\n widget.node.removeAttribute('aria-labelledby');\n }\n Private.removeAria = removeAria;\n /**\n * Normalize a tab area config and collect the visited widgets.\n */\n function normalizeTabAreaConfig(config, widgetSet) {\n // Bail early if there is no content.\n if (config.widgets.length === 0) {\n return null;\n }\n // Setup the filtered widgets array.\n let widgets = [];\n // Filter the config for unique widgets.\n for (const widget of config.widgets) {\n if (!widgetSet.has(widget)) {\n widgetSet.add(widget);\n widgets.push(widget);\n }\n }\n // Bail if there are no effective widgets.\n if (widgets.length === 0) {\n return null;\n }\n // Normalize the current index.\n let index = config.currentIndex;\n if (index !== -1 && (index < 0 || index >= widgets.length)) {\n index = 0;\n }\n // Return a normalized config object.\n return { type: 'tab-area', widgets, currentIndex: index };\n }\n /**\n * Normalize a split area config and collect the visited widgets.\n */\n function normalizeSplitAreaConfig(config, widgetSet) {\n // Set up the result variables.\n let orientation = config.orientation;\n let children = [];\n let sizes = [];\n // Normalize the config children.\n for (let i = 0, n = config.children.length; i < n; ++i) {\n // Normalize the child config.\n let child = normalizeAreaConfig(config.children[i], widgetSet);\n // Ignore an empty child.\n if (!child) {\n continue;\n }\n // Add the child or hoist its content as appropriate.\n if (child.type === 'tab-area' || child.orientation !== orientation) {\n children.push(child);\n sizes.push(Math.abs(config.sizes[i] || 0));\n }\n else {\n children.push(...child.children);\n sizes.push(...child.sizes);\n }\n }\n // Bail if there are no effective children.\n if (children.length === 0) {\n return null;\n }\n // If there is only one effective child, return that child.\n if (children.length === 1) {\n return children[0];\n }\n // Return a normalized config object.\n return { type: 'split-area', orientation, children, sizes };\n }\n /**\n * Convert a normalized tab area config into a layout tree.\n */\n function realizeTabAreaConfig(config, renderer, document) {\n // Create the tab bar for the layout node.\n let tabBar = renderer.createTabBar(document);\n // Hide each widget and add it to the tab bar.\n for (const widget of config.widgets) {\n widget.hide();\n tabBar.addTab(widget.title);\n Private.addAria(widget, tabBar);\n }\n // Set the current index of the tab bar.\n tabBar.currentIndex = config.currentIndex;\n // Return the new tab layout node.\n return new TabLayoutNode(tabBar);\n }\n /**\n * Convert a normalized split area config into a layout tree.\n */\n function realizeSplitAreaConfig(config, renderer, document) {\n // Create the split layout node.\n let node = new SplitLayoutNode(config.orientation);\n // Add each child to the layout node.\n config.children.forEach((child, i) => {\n // Create the child data for the layout node.\n let childNode = realizeAreaConfig(child, renderer, document);\n let sizer = createSizer(config.sizes[i]);\n let handle = renderer.createHandle();\n // Add the child data to the layout node.\n node.children.push(childNode);\n node.handles.push(handle);\n node.sizers.push(sizer);\n // Update the parent for the child node.\n childNode.parent = node;\n });\n // Synchronize the handle state for the layout node.\n node.syncHandles();\n // Normalize the sizes for the layout node.\n node.normalizeSizes();\n // Return the new layout node.\n return node;\n }\n})(Private$6 || (Private$6 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which provides a flexible docking area for widgets.\n */\nclass DockPanel extends Widget {\n /**\n * Construct a new dock panel.\n *\n * @param options - The options for initializing the panel.\n */\n constructor(options = {}) {\n super();\n this._drag = null;\n this._tabsMovable = true;\n this._tabsConstrained = false;\n this._addButtonEnabled = false;\n this._pressData = null;\n this._layoutModified = new Signal(this);\n this._addRequested = new Signal(this);\n this.addClass('lm-DockPanel');\n this._document = options.document || document;\n this._mode = options.mode || 'multiple-document';\n this._renderer = options.renderer || DockPanel.defaultRenderer;\n this._edges = options.edges || Private$5.DEFAULT_EDGES;\n if (options.tabsMovable !== undefined) {\n this._tabsMovable = options.tabsMovable;\n }\n if (options.tabsConstrained !== undefined) {\n this._tabsConstrained = options.tabsConstrained;\n }\n if (options.addButtonEnabled !== undefined) {\n this._addButtonEnabled = options.addButtonEnabled;\n }\n // Toggle the CSS mode attribute.\n this.dataset['mode'] = this._mode;\n // Create the delegate renderer for the layout.\n let renderer = {\n createTabBar: () => this._createTabBar(),\n createHandle: () => this._createHandle()\n };\n // Set up the dock layout for the panel.\n this.layout = new DockLayout({\n document: this._document,\n renderer,\n spacing: options.spacing,\n hiddenMode: options.hiddenMode\n });\n // Set up the overlay drop indicator.\n this.overlay = options.overlay || new DockPanel.Overlay();\n this.node.appendChild(this.overlay.node);\n }\n /**\n * Dispose of the resources held by the panel.\n */\n dispose() {\n // Ensure the mouse is released.\n this._releaseMouse();\n // Hide the overlay.\n this.overlay.hide(0);\n // Cancel a drag if one is in progress.\n if (this._drag) {\n this._drag.dispose();\n }\n // Dispose of the base class.\n super.dispose();\n }\n /**\n * The method for hiding widgets.\n */\n get hiddenMode() {\n return this.layout.hiddenMode;\n }\n /**\n * Set the method for hiding widgets.\n */\n set hiddenMode(v) {\n this.layout.hiddenMode = v;\n }\n /**\n * A signal emitted when the layout configuration is modified.\n *\n * #### Notes\n * This signal is emitted whenever the current layout configuration\n * may have changed.\n *\n * This signal is emitted asynchronously in a collapsed fashion, so\n * that multiple synchronous modifications results in only a single\n * emit of the signal.\n */\n get layoutModified() {\n return this._layoutModified;\n }\n /**\n * A signal emitted when the add button on a tab bar is clicked.\n *\n */\n get addRequested() {\n return this._addRequested;\n }\n /**\n * The renderer used by the dock panel.\n */\n get renderer() {\n return this.layout.renderer;\n }\n /**\n * Get the spacing between the widgets.\n */\n get spacing() {\n return this.layout.spacing;\n }\n /**\n * Set the spacing between the widgets.\n */\n set spacing(value) {\n this.layout.spacing = value;\n }\n /**\n * Get the mode for the dock panel.\n */\n get mode() {\n return this._mode;\n }\n /**\n * Set the mode for the dock panel.\n *\n * #### Notes\n * Changing the mode is a destructive operation with respect to the\n * panel's layout configuration. If layout state must be preserved,\n * save the current layout config before changing the mode.\n */\n set mode(value) {\n // Bail early if the mode does not change.\n if (this._mode === value) {\n return;\n }\n // Update the internal mode.\n this._mode = value;\n // Toggle the CSS mode attribute.\n this.dataset['mode'] = value;\n // Get the layout for the panel.\n let layout = this.layout;\n // Configure the layout for the specified mode.\n switch (value) {\n case 'multiple-document':\n for (const tabBar of layout.tabBars()) {\n tabBar.show();\n }\n break;\n case 'single-document':\n layout.restoreLayout(Private$5.createSingleDocumentConfig(this));\n break;\n default:\n throw 'unreachable';\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Whether the tabs can be dragged / moved at runtime.\n */\n get tabsMovable() {\n return this._tabsMovable;\n }\n /**\n * Enable / Disable draggable / movable tabs.\n */\n set tabsMovable(value) {\n this._tabsMovable = value;\n for (const tabBar of this.tabBars()) {\n tabBar.tabsMovable = value;\n }\n }\n /**\n * Whether the tabs are constrained to their source dock panel\n */\n get tabsConstrained() {\n return this._tabsConstrained;\n }\n /**\n * Constrain/Allow tabs to be dragged outside of this dock panel\n */\n set tabsConstrained(value) {\n this._tabsConstrained = value;\n }\n /**\n * Whether the add buttons for each tab bar are enabled.\n */\n get addButtonEnabled() {\n return this._addButtonEnabled;\n }\n /**\n * Set whether the add buttons for each tab bar are enabled.\n */\n set addButtonEnabled(value) {\n this._addButtonEnabled = value;\n for (const tabBar of this.tabBars()) {\n tabBar.addButtonEnabled = value;\n }\n }\n /**\n * Whether the dock panel is empty.\n */\n get isEmpty() {\n return this.layout.isEmpty;\n }\n /**\n * Create an iterator over the user widgets in the panel.\n *\n * @returns A new iterator over the user widgets in the panel.\n *\n * #### Notes\n * This iterator does not include the generated tab bars.\n */\n *widgets() {\n yield* this.layout.widgets();\n }\n /**\n * Create an iterator over the selected widgets in the panel.\n *\n * @returns A new iterator over the selected user widgets.\n *\n * #### Notes\n * This iterator yields the widgets corresponding to the current tab\n * of each tab bar in the panel.\n */\n *selectedWidgets() {\n yield* this.layout.selectedWidgets();\n }\n /**\n * Create an iterator over the tab bars in the panel.\n *\n * @returns A new iterator over the tab bars in the panel.\n *\n * #### Notes\n * This iterator does not include the user widgets.\n */\n *tabBars() {\n yield* this.layout.tabBars();\n }\n /**\n * Create an iterator over the handles in the panel.\n *\n * @returns A new iterator over the handles in the panel.\n */\n *handles() {\n yield* this.layout.handles();\n }\n /**\n * Select a specific widget in the dock panel.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * This will make the widget the current widget in its tab area.\n */\n selectWidget(widget) {\n // Find the tab bar which contains the widget.\n let tabBar = find(this.tabBars(), bar => {\n return bar.titles.indexOf(widget.title) !== -1;\n });\n // Throw an error if no tab bar is found.\n if (!tabBar) {\n throw new Error('Widget is not contained in the dock panel.');\n }\n // Ensure the widget is the current widget.\n tabBar.currentTitle = widget.title;\n }\n /**\n * Activate a specified widget in the dock panel.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * This will select and activate the given widget.\n */\n activateWidget(widget) {\n this.selectWidget(widget);\n widget.activate();\n }\n /**\n * Save the current layout configuration of the dock panel.\n *\n * @returns A new config object for the current layout state.\n *\n * #### Notes\n * The return value can be provided to the `restoreLayout` method\n * in order to restore the layout to its current configuration.\n */\n saveLayout() {\n return this.layout.saveLayout();\n }\n /**\n * Restore the layout to a previously saved configuration.\n *\n * @param config - The layout configuration to restore.\n *\n * #### Notes\n * Widgets which currently belong to the layout but which are not\n * contained in the config will be unparented.\n *\n * The dock panel automatically reverts to `'multiple-document'`\n * mode when a layout config is restored.\n */\n restoreLayout(config) {\n // Reset the mode.\n this._mode = 'multiple-document';\n // Restore the layout.\n this.layout.restoreLayout(config);\n // Flush the message loop on IE and Edge to prevent flicker.\n if (Platform.IS_EDGE || Platform.IS_IE) {\n MessageLoop.flush();\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Add a widget to the dock panel.\n *\n * @param widget - The widget to add to the dock panel.\n *\n * @param options - The additional options for adding the widget.\n *\n * #### Notes\n * If the panel is in single document mode, the options are ignored\n * and the widget is always added as tab in the hidden tab bar.\n */\n addWidget(widget, options = {}) {\n // Add the widget to the layout.\n if (this._mode === 'single-document') {\n this.layout.addWidget(widget);\n }\n else {\n this.layout.addWidget(widget, options);\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Process a message sent to the widget.\n *\n * @param msg - The message sent to the widget.\n */\n processMessage(msg) {\n if (msg.type === 'layout-modified') {\n this._layoutModified.emit(undefined);\n }\n else {\n super.processMessage(msg);\n }\n }\n /**\n * Handle the DOM events for the dock panel.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the panel's DOM node. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'lm-dragenter':\n this._evtDragEnter(event);\n break;\n case 'lm-dragleave':\n this._evtDragLeave(event);\n break;\n case 'lm-dragover':\n this._evtDragOver(event);\n break;\n case 'lm-drop':\n this._evtDrop(event);\n break;\n case 'pointerdown':\n this._evtPointerDown(event);\n break;\n case 'pointermove':\n this._evtPointerMove(event);\n break;\n case 'pointerup':\n this._evtPointerUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('lm-dragenter', this);\n this.node.addEventListener('lm-dragleave', this);\n this.node.addEventListener('lm-dragover', this);\n this.node.addEventListener('lm-drop', this);\n this.node.addEventListener('pointerdown', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('lm-dragenter', this);\n this.node.removeEventListener('lm-dragleave', this);\n this.node.removeEventListener('lm-dragover', this);\n this.node.removeEventListener('lm-drop', this);\n this.node.removeEventListener('pointerdown', this);\n this._releaseMouse();\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n // Ignore the generated tab bars.\n if (Private$5.isGeneratedTabBarProperty.get(msg.child)) {\n return;\n }\n // Add the widget class to the child.\n msg.child.addClass('lm-DockPanel-widget');\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n // Ignore the generated tab bars.\n if (Private$5.isGeneratedTabBarProperty.get(msg.child)) {\n return;\n }\n // Remove the widget class from the child.\n msg.child.removeClass('lm-DockPanel-widget');\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Handle the `'lm-dragenter'` event for the dock panel.\n */\n _evtDragEnter(event) {\n // If the factory mime type is present, mark the event as\n // handled in order to get the rest of the drag events.\n if (event.mimeData.hasData('application/vnd.lumino.widget-factory')) {\n event.preventDefault();\n event.stopPropagation();\n }\n }\n /**\n * Handle the `'lm-dragleave'` event for the dock panel.\n */\n _evtDragLeave(event) {\n // Mark the event as handled.\n event.preventDefault();\n if (this._tabsConstrained && event.source !== this)\n return;\n event.stopPropagation();\n // The new target might be a descendant, so we might still handle the drop.\n // Hide asynchronously so that if a lm-dragover event bubbles up to us, the\n // hide is cancelled by the lm-dragover handler's show overlay logic.\n this.overlay.hide(1);\n }\n /**\n * Handle the `'lm-dragover'` event for the dock panel.\n */\n _evtDragOver(event) {\n // Mark the event as handled.\n event.preventDefault();\n // Show the drop indicator overlay and update the drop\n // action based on the drop target zone under the mouse.\n if ((this._tabsConstrained && event.source !== this) ||\n this._showOverlay(event.clientX, event.clientY) === 'invalid') {\n event.dropAction = 'none';\n }\n else {\n event.stopPropagation();\n event.dropAction = event.proposedAction;\n }\n }\n /**\n * Handle the `'lm-drop'` event for the dock panel.\n */\n _evtDrop(event) {\n // Mark the event as handled.\n event.preventDefault();\n // Hide the drop indicator overlay.\n this.overlay.hide(0);\n // Bail if the proposed action is to do nothing.\n if (event.proposedAction === 'none') {\n event.dropAction = 'none';\n return;\n }\n // Find the drop target under the mouse.\n let { clientX, clientY } = event;\n let { zone, target } = Private$5.findDropTarget(this, clientX, clientY, this._edges);\n // Bail if the drop zone is invalid.\n if ((this._tabsConstrained && event.source !== this) ||\n zone === 'invalid') {\n event.dropAction = 'none';\n return;\n }\n // Bail if the factory mime type has invalid data.\n let mimeData = event.mimeData;\n let factory = mimeData.getData('application/vnd.lumino.widget-factory');\n if (typeof factory !== 'function') {\n event.dropAction = 'none';\n return;\n }\n // Bail if the factory does not produce a widget.\n let widget = factory();\n if (!(widget instanceof Widget)) {\n event.dropAction = 'none';\n return;\n }\n // Bail if the widget is an ancestor of the dock panel.\n if (widget.contains(this)) {\n event.dropAction = 'none';\n return;\n }\n // Find the reference widget for the drop target.\n let ref = target ? Private$5.getDropRef(target.tabBar) : null;\n // Add the widget according to the indicated drop zone.\n switch (zone) {\n case 'root-all':\n this.addWidget(widget);\n break;\n case 'root-top':\n this.addWidget(widget, { mode: 'split-top' });\n break;\n case 'root-left':\n this.addWidget(widget, { mode: 'split-left' });\n break;\n case 'root-right':\n this.addWidget(widget, { mode: 'split-right' });\n break;\n case 'root-bottom':\n this.addWidget(widget, { mode: 'split-bottom' });\n break;\n case 'widget-all':\n this.addWidget(widget, { mode: 'tab-after', ref });\n break;\n case 'widget-top':\n this.addWidget(widget, { mode: 'split-top', ref });\n break;\n case 'widget-left':\n this.addWidget(widget, { mode: 'split-left', ref });\n break;\n case 'widget-right':\n this.addWidget(widget, { mode: 'split-right', ref });\n break;\n case 'widget-bottom':\n this.addWidget(widget, { mode: 'split-bottom', ref });\n break;\n case 'widget-tab':\n this.addWidget(widget, { mode: 'tab-after', ref });\n break;\n default:\n throw 'unreachable';\n }\n // Accept the proposed drop action.\n event.dropAction = event.proposedAction;\n // Stop propagation if we have not bailed so far.\n event.stopPropagation();\n // Activate the dropped widget.\n this.activateWidget(widget);\n }\n /**\n * Handle the `'keydown'` event for the dock panel.\n */\n _evtKeyDown(event) {\n // Stop input events during drag.\n event.preventDefault();\n event.stopPropagation();\n // Release the mouse if `Escape` is pressed.\n if (event.keyCode === 27) {\n // Finalize the mouse release.\n this._releaseMouse();\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n }\n /**\n * Handle the `'pointerdown'` event for the dock panel.\n */\n _evtPointerDown(event) {\n // Do nothing if the left mouse button is not pressed.\n if (event.button !== 0) {\n return;\n }\n // Find the handle which contains the mouse target, if any.\n let layout = this.layout;\n let target = event.target;\n let handle = find(layout.handles(), handle => handle.contains(target));\n if (!handle) {\n return;\n }\n // Stop the event when a handle is pressed.\n event.preventDefault();\n event.stopPropagation();\n // Add the extra document listeners.\n this._document.addEventListener('keydown', this, true);\n this._document.addEventListener('pointerup', this, true);\n this._document.addEventListener('pointermove', this, true);\n this._document.addEventListener('contextmenu', this, true);\n // Compute the offset deltas for the handle press.\n let rect = handle.getBoundingClientRect();\n let deltaX = event.clientX - rect.left;\n let deltaY = event.clientY - rect.top;\n // Override the cursor and store the press data.\n let style = window.getComputedStyle(handle);\n let override = Drag.overrideCursor(style.cursor, this._document);\n this._pressData = { handle, deltaX, deltaY, override };\n }\n /**\n * Handle the `'pointermove'` event for the dock panel.\n */\n _evtPointerMove(event) {\n // Bail early if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Stop the event when dragging a handle.\n event.preventDefault();\n event.stopPropagation();\n // Compute the desired offset position for the handle.\n let rect = this.node.getBoundingClientRect();\n let xPos = event.clientX - rect.left - this._pressData.deltaX;\n let yPos = event.clientY - rect.top - this._pressData.deltaY;\n // Set the handle as close to the desired position as possible.\n let layout = this.layout;\n layout.moveHandle(this._pressData.handle, xPos, yPos);\n }\n /**\n * Handle the `'pointerup'` event for the dock panel.\n */\n _evtPointerUp(event) {\n // Do nothing if the left mouse button is not released.\n if (event.button !== 0) {\n return;\n }\n // Stop the event when releasing a handle.\n event.preventDefault();\n event.stopPropagation();\n // Finalize the mouse release.\n this._releaseMouse();\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Release the mouse grab for the dock panel.\n */\n _releaseMouse() {\n // Bail early if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Clear the override cursor.\n this._pressData.override.dispose();\n this._pressData = null;\n // Remove the extra document listeners.\n this._document.removeEventListener('keydown', this, true);\n this._document.removeEventListener('pointerup', this, true);\n this._document.removeEventListener('pointermove', this, true);\n this._document.removeEventListener('contextmenu', this, true);\n }\n /**\n * Show the overlay indicator at the given client position.\n *\n * Returns the drop zone at the specified client position.\n *\n * #### Notes\n * If the position is not over a valid zone, the overlay is hidden.\n */\n _showOverlay(clientX, clientY) {\n // Find the dock target for the given client position.\n let { zone, target } = Private$5.findDropTarget(this, clientX, clientY, this._edges);\n // If the drop zone is invalid, hide the overlay and bail.\n if (zone === 'invalid') {\n this.overlay.hide(100);\n return zone;\n }\n // Setup the variables needed to compute the overlay geometry.\n let top;\n let left;\n let right;\n let bottom;\n let box = ElementExt.boxSizing(this.node); // TODO cache this?\n let rect = this.node.getBoundingClientRect();\n // Compute the overlay geometry based on the dock zone.\n switch (zone) {\n case 'root-all':\n top = box.paddingTop;\n left = box.paddingLeft;\n right = box.paddingRight;\n bottom = box.paddingBottom;\n break;\n case 'root-top':\n top = box.paddingTop;\n left = box.paddingLeft;\n right = box.paddingRight;\n bottom = rect.height * Private$5.GOLDEN_RATIO;\n break;\n case 'root-left':\n top = box.paddingTop;\n left = box.paddingLeft;\n right = rect.width * Private$5.GOLDEN_RATIO;\n bottom = box.paddingBottom;\n break;\n case 'root-right':\n top = box.paddingTop;\n left = rect.width * Private$5.GOLDEN_RATIO;\n right = box.paddingRight;\n bottom = box.paddingBottom;\n break;\n case 'root-bottom':\n top = rect.height * Private$5.GOLDEN_RATIO;\n left = box.paddingLeft;\n right = box.paddingRight;\n bottom = box.paddingBottom;\n break;\n case 'widget-all':\n top = target.top;\n left = target.left;\n right = target.right;\n bottom = target.bottom;\n break;\n case 'widget-top':\n top = target.top;\n left = target.left;\n right = target.right;\n bottom = target.bottom + target.height / 2;\n break;\n case 'widget-left':\n top = target.top;\n left = target.left;\n right = target.right + target.width / 2;\n bottom = target.bottom;\n break;\n case 'widget-right':\n top = target.top;\n left = target.left + target.width / 2;\n right = target.right;\n bottom = target.bottom;\n break;\n case 'widget-bottom':\n top = target.top + target.height / 2;\n left = target.left;\n right = target.right;\n bottom = target.bottom;\n break;\n case 'widget-tab': {\n const tabHeight = target.tabBar.node.getBoundingClientRect().height;\n top = target.top;\n left = target.left;\n right = target.right;\n bottom = target.bottom + target.height - tabHeight;\n break;\n }\n default:\n throw 'unreachable';\n }\n // Show the overlay with the computed geometry.\n this.overlay.show({ top, left, right, bottom });\n // Finally, return the computed drop zone.\n return zone;\n }\n /**\n * Create a new tab bar for use by the panel.\n */\n _createTabBar() {\n // Create the tab bar.\n let tabBar = this._renderer.createTabBar(this._document);\n // Set the generated tab bar property for the tab bar.\n Private$5.isGeneratedTabBarProperty.set(tabBar, true);\n // Hide the tab bar when in single document mode.\n if (this._mode === 'single-document') {\n tabBar.hide();\n }\n // Enforce necessary tab bar behavior.\n // TODO do we really want to enforce *all* of these?\n tabBar.tabsMovable = this._tabsMovable;\n tabBar.allowDeselect = false;\n tabBar.addButtonEnabled = this._addButtonEnabled;\n tabBar.removeBehavior = 'select-previous-tab';\n tabBar.insertBehavior = 'select-tab-if-needed';\n // Connect the signal handlers for the tab bar.\n tabBar.tabMoved.connect(this._onTabMoved, this);\n tabBar.currentChanged.connect(this._onCurrentChanged, this);\n tabBar.tabCloseRequested.connect(this._onTabCloseRequested, this);\n tabBar.tabDetachRequested.connect(this._onTabDetachRequested, this);\n tabBar.tabActivateRequested.connect(this._onTabActivateRequested, this);\n tabBar.addRequested.connect(this._onTabAddRequested, this);\n // Return the initialized tab bar.\n return tabBar;\n }\n /**\n * Create a new handle for use by the panel.\n */\n _createHandle() {\n return this._renderer.createHandle();\n }\n /**\n * Handle the `tabMoved` signal from a tab bar.\n */\n _onTabMoved() {\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Handle the `currentChanged` signal from a tab bar.\n */\n _onCurrentChanged(sender, args) {\n // Extract the previous and current title from the args.\n let { previousTitle, currentTitle } = args;\n // Hide the previous widget.\n if (previousTitle) {\n previousTitle.owner.hide();\n }\n // Show the current widget.\n if (currentTitle) {\n currentTitle.owner.show();\n }\n // Flush the message loop on IE and Edge to prevent flicker.\n if (Platform.IS_EDGE || Platform.IS_IE) {\n MessageLoop.flush();\n }\n // Schedule an emit of the layout modified signal.\n MessageLoop.postMessage(this, Private$5.LayoutModified);\n }\n /**\n * Handle the `addRequested` signal from a tab bar.\n */\n _onTabAddRequested(sender) {\n this._addRequested.emit(sender);\n }\n /**\n * Handle the `tabActivateRequested` signal from a tab bar.\n */\n _onTabActivateRequested(sender, args) {\n args.title.owner.activate();\n }\n /**\n * Handle the `tabCloseRequested` signal from a tab bar.\n */\n _onTabCloseRequested(sender, args) {\n args.title.owner.close();\n }\n /**\n * Handle the `tabDetachRequested` signal from a tab bar.\n */\n _onTabDetachRequested(sender, args) {\n // Do nothing if a drag is already in progress.\n if (this._drag) {\n return;\n }\n // Release the tab bar's hold on the mouse.\n sender.releaseMouse();\n // Extract the data from the args.\n let { title, tab, clientX, clientY, offset } = args;\n // Setup the mime data for the drag operation.\n let mimeData = new MimeData();\n let factory = () => title.owner;\n mimeData.setData('application/vnd.lumino.widget-factory', factory);\n // Create the drag image for the drag operation.\n let dragImage = tab.cloneNode(true);\n if (offset) {\n dragImage.style.top = `-${offset.y}px`;\n dragImage.style.left = `-${offset.x}px`;\n }\n // Create the drag object to manage the drag-drop operation.\n this._drag = new Drag({\n document: this._document,\n mimeData,\n dragImage,\n proposedAction: 'move',\n supportedActions: 'move',\n source: this\n });\n // Hide the tab node in the original tab.\n tab.classList.add('lm-mod-hidden');\n let cleanup = () => {\n this._drag = null;\n tab.classList.remove('lm-mod-hidden');\n };\n // Start the drag operation and cleanup when done.\n this._drag.start(clientX, clientY).then(cleanup);\n }\n}\n/**\n * The namespace for the `DockPanel` class statics.\n */\n(function (DockPanel) {\n /**\n * A concrete implementation of `IOverlay`.\n *\n * This is the default overlay implementation for a dock panel.\n */\n class Overlay {\n /**\n * Construct a new overlay.\n */\n constructor() {\n this._timer = -1;\n this._hidden = true;\n this.node = document.createElement('div');\n this.node.classList.add('lm-DockPanel-overlay');\n this.node.classList.add('lm-mod-hidden');\n this.node.style.position = 'absolute';\n this.node.style.contain = 'strict';\n }\n /**\n * Show the overlay using the given overlay geometry.\n *\n * @param geo - The desired geometry for the overlay.\n */\n show(geo) {\n // Update the position of the overlay.\n let style = this.node.style;\n style.top = `${geo.top}px`;\n style.left = `${geo.left}px`;\n style.right = `${geo.right}px`;\n style.bottom = `${geo.bottom}px`;\n // Clear any pending hide timer.\n clearTimeout(this._timer);\n this._timer = -1;\n // If the overlay is already visible, we're done.\n if (!this._hidden) {\n return;\n }\n // Clear the hidden flag.\n this._hidden = false;\n // Finally, show the overlay.\n this.node.classList.remove('lm-mod-hidden');\n }\n /**\n * Hide the overlay node.\n *\n * @param delay - The delay (in ms) before hiding the overlay.\n * A delay value <= 0 will hide the overlay immediately.\n */\n hide(delay) {\n // Do nothing if the overlay is already hidden.\n if (this._hidden) {\n return;\n }\n // Hide immediately if the delay is <= 0.\n if (delay <= 0) {\n clearTimeout(this._timer);\n this._timer = -1;\n this._hidden = true;\n this.node.classList.add('lm-mod-hidden');\n return;\n }\n // Do nothing if a hide is already pending.\n if (this._timer !== -1) {\n return;\n }\n // Otherwise setup the hide timer.\n this._timer = window.setTimeout(() => {\n this._timer = -1;\n this._hidden = true;\n this.node.classList.add('lm-mod-hidden');\n }, delay);\n }\n }\n DockPanel.Overlay = Overlay;\n /**\n * The default implementation of `IRenderer`.\n */\n class Renderer {\n /**\n * Create a new tab bar for use with a dock panel.\n *\n * @returns A new tab bar for a dock panel.\n */\n createTabBar(document) {\n let bar = new TabBar({ document });\n bar.addClass('lm-DockPanel-tabBar');\n return bar;\n }\n /**\n * Create a new handle node for use with a dock panel.\n *\n * @returns A new handle node for a dock panel.\n */\n createHandle() {\n let handle = document.createElement('div');\n handle.className = 'lm-DockPanel-handle';\n return handle;\n }\n }\n DockPanel.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n DockPanel.defaultRenderer = new Renderer();\n})(DockPanel || (DockPanel = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$5;\n(function (Private) {\n /**\n * A fraction used for sizing root panels; ~= `1 / golden_ratio`.\n */\n Private.GOLDEN_RATIO = 0.618;\n /**\n * The default sizes for the edge drop zones, in pixels.\n */\n Private.DEFAULT_EDGES = {\n /**\n * The size of the top edge dock zone for the root panel, in pixels.\n * This is different from the others to distinguish between the top\n * tab bar and the top root zone.\n */\n top: 12,\n /**\n * The size of the edge dock zone for the root panel, in pixels.\n */\n right: 40,\n /**\n * The size of the edge dock zone for the root panel, in pixels.\n */\n bottom: 40,\n /**\n * The size of the edge dock zone for the root panel, in pixels.\n */\n left: 40\n };\n /**\n * A singleton `'layout-modified'` conflatable message.\n */\n Private.LayoutModified = new ConflatableMessage('layout-modified');\n /**\n * An attached property used to track generated tab bars.\n */\n Private.isGeneratedTabBarProperty = new AttachedProperty({\n name: 'isGeneratedTabBar',\n create: () => false\n });\n /**\n * Create a single document config for the widgets in a dock panel.\n */\n function createSingleDocumentConfig(panel) {\n // Return an empty config if the panel is empty.\n if (panel.isEmpty) {\n return { main: null };\n }\n // Get a flat array of the widgets in the panel.\n let widgets = Array.from(panel.widgets());\n // Get the first selected widget in the panel.\n let selected = panel.selectedWidgets().next().value;\n // Compute the current index for the new config.\n let currentIndex = selected ? widgets.indexOf(selected) : -1;\n // Return the single document config.\n return { main: { type: 'tab-area', widgets, currentIndex } };\n }\n Private.createSingleDocumentConfig = createSingleDocumentConfig;\n /**\n * Find the drop target at the given client position.\n */\n function findDropTarget(panel, clientX, clientY, edges) {\n // Bail if the mouse is not over the dock panel.\n if (!ElementExt.hitTest(panel.node, clientX, clientY)) {\n return { zone: 'invalid', target: null };\n }\n // Look up the layout for the panel.\n let layout = panel.layout;\n // If the layout is empty, indicate the entire root drop zone.\n if (layout.isEmpty) {\n return { zone: 'root-all', target: null };\n }\n // Test the edge zones when in multiple document mode.\n if (panel.mode === 'multiple-document') {\n // Get the client rect for the dock panel.\n let panelRect = panel.node.getBoundingClientRect();\n // Compute the distance to each edge of the panel.\n let pl = clientX - panelRect.left + 1;\n let pt = clientY - panelRect.top + 1;\n let pr = panelRect.right - clientX;\n let pb = panelRect.bottom - clientY;\n // Find the minimum distance to an edge.\n let pd = Math.min(pt, pr, pb, pl);\n // Return a root zone if the mouse is within an edge.\n switch (pd) {\n case pt:\n if (pt < edges.top) {\n return { zone: 'root-top', target: null };\n }\n break;\n case pr:\n if (pr < edges.right) {\n return { zone: 'root-right', target: null };\n }\n break;\n case pb:\n if (pb < edges.bottom) {\n return { zone: 'root-bottom', target: null };\n }\n break;\n case pl:\n if (pl < edges.left) {\n return { zone: 'root-left', target: null };\n }\n break;\n default:\n throw 'unreachable';\n }\n }\n // Hit test the dock layout at the given client position.\n let target = layout.hitTestTabAreas(clientX, clientY);\n // Bail if no target area was found.\n if (!target) {\n return { zone: 'invalid', target: null };\n }\n // Return the whole tab area when in single document mode.\n if (panel.mode === 'single-document') {\n return { zone: 'widget-all', target };\n }\n // Compute the distance to each edge of the tab area.\n let al = target.x - target.left + 1;\n let at = target.y - target.top + 1;\n let ar = target.left + target.width - target.x;\n let ab = target.top + target.height - target.y;\n const tabHeight = target.tabBar.node.getBoundingClientRect().height;\n if (at < tabHeight) {\n return { zone: 'widget-tab', target };\n }\n // Get the X and Y edge sizes for the area.\n let rx = Math.round(target.width / 3);\n let ry = Math.round(target.height / 3);\n // If the mouse is not within an edge, indicate the entire area.\n if (al > rx && ar > rx && at > ry && ab > ry) {\n return { zone: 'widget-all', target };\n }\n // Scale the distances by the slenderness ratio.\n al /= rx;\n at /= ry;\n ar /= rx;\n ab /= ry;\n // Find the minimum distance to the area edge.\n let ad = Math.min(al, at, ar, ab);\n // Find the widget zone for the area edge.\n let zone;\n switch (ad) {\n case al:\n zone = 'widget-left';\n break;\n case at:\n zone = 'widget-top';\n break;\n case ar:\n zone = 'widget-right';\n break;\n case ab:\n zone = 'widget-bottom';\n break;\n default:\n throw 'unreachable';\n }\n // Return the final drop target.\n return { zone, target };\n }\n Private.findDropTarget = findDropTarget;\n /**\n * Get the drop reference widget for a tab bar.\n */\n function getDropRef(tabBar) {\n if (tabBar.titles.length === 0) {\n return null;\n }\n if (tabBar.currentTitle) {\n return tabBar.currentTitle.owner;\n }\n return tabBar.titles[tabBar.titles.length - 1].owner;\n }\n Private.getDropRef = getDropRef;\n})(Private$5 || (Private$5 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A class which tracks focus among a set of widgets.\n *\n * This class is useful when code needs to keep track of the most\n * recently focused widget(s) among a set of related widgets.\n */\nclass FocusTracker {\n constructor() {\n this._counter = 0;\n this._widgets = [];\n this._activeWidget = null;\n this._currentWidget = null;\n this._numbers = new Map();\n this._nodes = new Map();\n this._activeChanged = new Signal(this);\n this._currentChanged = new Signal(this);\n }\n /**\n * Dispose of the resources held by the tracker.\n */\n dispose() {\n // Do nothing if the tracker is already disposed.\n if (this._counter < 0) {\n return;\n }\n // Mark the tracker as disposed.\n this._counter = -1;\n // Clear the connections for the tracker.\n Signal.clearData(this);\n // Remove all event listeners.\n for (const widget of this._widgets) {\n widget.node.removeEventListener('focus', this, true);\n widget.node.removeEventListener('blur', this, true);\n }\n // Clear the internal data structures.\n this._activeWidget = null;\n this._currentWidget = null;\n this._nodes.clear();\n this._numbers.clear();\n this._widgets.length = 0;\n }\n /**\n * A signal emitted when the current widget has changed.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * A signal emitted when the active widget has changed.\n */\n get activeChanged() {\n return this._activeChanged;\n }\n /**\n * A flag indicating whether the tracker is disposed.\n */\n get isDisposed() {\n return this._counter < 0;\n }\n /**\n * The current widget in the tracker.\n *\n * #### Notes\n * The current widget is the widget among the tracked widgets which\n * has the *descendant node* which has most recently been focused.\n *\n * The current widget will not be updated if the node loses focus. It\n * will only be updated when a different tracked widget gains focus.\n *\n * If the current widget is removed from the tracker, the previous\n * current widget will be restored.\n *\n * This behavior is intended to follow a user's conceptual model of\n * a semantically \"current\" widget, where the \"last thing of type X\"\n * to be interacted with is the \"current instance of X\", regardless\n * of whether that instance still has focus.\n */\n get currentWidget() {\n return this._currentWidget;\n }\n /**\n * The active widget in the tracker.\n *\n * #### Notes\n * The active widget is the widget among the tracked widgets which\n * has the *descendant node* which is currently focused.\n */\n get activeWidget() {\n return this._activeWidget;\n }\n /**\n * A read only array of the widgets being tracked.\n */\n get widgets() {\n return this._widgets;\n }\n /**\n * Get the focus number for a particular widget in the tracker.\n *\n * @param widget - The widget of interest.\n *\n * @returns The focus number for the given widget, or `-1` if the\n * widget has not had focus since being added to the tracker, or\n * is not contained by the tracker.\n *\n * #### Notes\n * The focus number indicates the relative order in which the widgets\n * have gained focus. A widget with a larger number has gained focus\n * more recently than a widget with a smaller number.\n *\n * The `currentWidget` will always have the largest focus number.\n *\n * All widgets start with a focus number of `-1`, which indicates that\n * the widget has not been focused since being added to the tracker.\n */\n focusNumber(widget) {\n let n = this._numbers.get(widget);\n return n === undefined ? -1 : n;\n }\n /**\n * Test whether the focus tracker contains a given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns `true` if the widget is tracked, `false` otherwise.\n */\n has(widget) {\n return this._numbers.has(widget);\n }\n /**\n * Add a widget to the focus tracker.\n *\n * @param widget - The widget of interest.\n *\n * #### Notes\n * A widget will be automatically removed from the tracker if it\n * is disposed after being added.\n *\n * If the widget is already tracked, this is a no-op.\n */\n add(widget) {\n // Do nothing if the widget is already tracked.\n if (this._numbers.has(widget)) {\n return;\n }\n // Test whether the widget has focus.\n let focused = widget.node.contains(document.activeElement);\n // Set up the initial focus number.\n let n = focused ? this._counter++ : -1;\n // Add the widget to the internal data structures.\n this._widgets.push(widget);\n this._numbers.set(widget, n);\n this._nodes.set(widget.node, widget);\n // Set up the event listeners. The capturing phase must be used\n // since the 'focus' and 'blur' events don't bubble and Firefox\n // doesn't support the 'focusin' or 'focusout' events.\n widget.node.addEventListener('focus', this, true);\n widget.node.addEventListener('blur', this, true);\n // Connect the disposed signal handler.\n widget.disposed.connect(this._onWidgetDisposed, this);\n // Set the current and active widgets if needed.\n if (focused) {\n this._setWidgets(widget, widget);\n }\n }\n /**\n * Remove a widget from the focus tracker.\n *\n * #### Notes\n * If the widget is the `currentWidget`, the previous current widget\n * will become the new `currentWidget`.\n *\n * A widget will be automatically removed from the tracker if it\n * is disposed after being added.\n *\n * If the widget is not tracked, this is a no-op.\n */\n remove(widget) {\n // Bail early if the widget is not tracked.\n if (!this._numbers.has(widget)) {\n return;\n }\n // Disconnect the disposed signal handler.\n widget.disposed.disconnect(this._onWidgetDisposed, this);\n // Remove the event listeners.\n widget.node.removeEventListener('focus', this, true);\n widget.node.removeEventListener('blur', this, true);\n // Remove the widget from the internal data structures.\n ArrayExt.removeFirstOf(this._widgets, widget);\n this._nodes.delete(widget.node);\n this._numbers.delete(widget);\n // Bail early if the widget is not the current widget.\n if (this._currentWidget !== widget) {\n return;\n }\n // Filter the widgets for those which have had focus.\n let valid = this._widgets.filter(w => this._numbers.get(w) !== -1);\n // Get the valid widget with the max focus number.\n let previous = max(valid, (first, second) => {\n let a = this._numbers.get(first);\n let b = this._numbers.get(second);\n return a - b;\n }) || null;\n // Set the current and active widgets.\n this._setWidgets(previous, null);\n }\n /**\n * Handle the DOM events for the focus tracker.\n *\n * @param event - The DOM event sent to the panel.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the tracked nodes. It should\n * not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'focus':\n this._evtFocus(event);\n break;\n case 'blur':\n this._evtBlur(event);\n break;\n }\n }\n /**\n * Set the current and active widgets for the tracker.\n */\n _setWidgets(current, active) {\n // Swap the current widget.\n let oldCurrent = this._currentWidget;\n this._currentWidget = current;\n // Swap the active widget.\n let oldActive = this._activeWidget;\n this._activeWidget = active;\n // Emit the `currentChanged` signal if needed.\n if (oldCurrent !== current) {\n this._currentChanged.emit({ oldValue: oldCurrent, newValue: current });\n }\n // Emit the `activeChanged` signal if needed.\n if (oldActive !== active) {\n this._activeChanged.emit({ oldValue: oldActive, newValue: active });\n }\n }\n /**\n * Handle the `'focus'` event for a tracked widget.\n */\n _evtFocus(event) {\n // Find the widget which gained focus, which is known to exist.\n let widget = this._nodes.get(event.currentTarget);\n // Update the focus number if necessary.\n if (widget !== this._currentWidget) {\n this._numbers.set(widget, this._counter++);\n }\n // Set the current and active widgets.\n this._setWidgets(widget, widget);\n }\n /**\n * Handle the `'blur'` event for a tracked widget.\n */\n _evtBlur(event) {\n // Find the widget which lost focus, which is known to exist.\n let widget = this._nodes.get(event.currentTarget);\n // Get the node which being focused after this blur.\n let focusTarget = event.relatedTarget;\n // If no other node is being focused, clear the active widget.\n if (!focusTarget) {\n this._setWidgets(this._currentWidget, null);\n return;\n }\n // Bail if the focus widget is not changing.\n if (widget.node.contains(focusTarget)) {\n return;\n }\n // If no tracked widget is being focused, clear the active widget.\n if (!find(this._widgets, w => w.node.contains(focusTarget))) {\n this._setWidgets(this._currentWidget, null);\n return;\n }\n }\n /**\n * Handle the `disposed` signal for a tracked widget.\n */\n _onWidgetDisposed(sender) {\n this.remove(sender);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout which arranges its widgets in a grid.\n */\nclass GridLayout extends Layout {\n /**\n * Construct a new grid layout.\n *\n * @param options - The options for initializing the layout.\n */\n constructor(options = {}) {\n super(options);\n this._dirty = false;\n this._rowSpacing = 4;\n this._columnSpacing = 4;\n this._items = [];\n this._rowStarts = [];\n this._columnStarts = [];\n this._rowSizers = [new BoxSizer()];\n this._columnSizers = [new BoxSizer()];\n this._box = null;\n if (options.rowCount !== undefined) {\n Private$4.reallocSizers(this._rowSizers, options.rowCount);\n }\n if (options.columnCount !== undefined) {\n Private$4.reallocSizers(this._columnSizers, options.columnCount);\n }\n if (options.rowSpacing !== undefined) {\n this._rowSpacing = Private$4.clampValue(options.rowSpacing);\n }\n if (options.columnSpacing !== undefined) {\n this._columnSpacing = Private$4.clampValue(options.columnSpacing);\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the widgets and layout items.\n for (const item of this._items) {\n let widget = item.widget;\n item.dispose();\n widget.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n this._rowStarts.length = 0;\n this._rowSizers.length = 0;\n this._columnStarts.length = 0;\n this._columnSizers.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Get the number of rows in the layout.\n */\n get rowCount() {\n return this._rowSizers.length;\n }\n /**\n * Set the number of rows in the layout.\n *\n * #### Notes\n * The minimum row count is `1`.\n */\n set rowCount(value) {\n // Do nothing if the row count does not change.\n if (value === this.rowCount) {\n return;\n }\n // Reallocate the row sizers.\n Private$4.reallocSizers(this._rowSizers, value);\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the number of columns in the layout.\n */\n get columnCount() {\n return this._columnSizers.length;\n }\n /**\n * Set the number of columns in the layout.\n *\n * #### Notes\n * The minimum column count is `1`.\n */\n set columnCount(value) {\n // Do nothing if the column count does not change.\n if (value === this.columnCount) {\n return;\n }\n // Reallocate the column sizers.\n Private$4.reallocSizers(this._columnSizers, value);\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the row spacing for the layout.\n */\n get rowSpacing() {\n return this._rowSpacing;\n }\n /**\n * Set the row spacing for the layout.\n */\n set rowSpacing(value) {\n // Clamp the spacing to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the spacing does not change\n if (this._rowSpacing === value) {\n return;\n }\n // Update the internal spacing.\n this._rowSpacing = value;\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the column spacing for the layout.\n */\n get columnSpacing() {\n return this._columnSpacing;\n }\n /**\n * Set the col spacing for the layout.\n */\n set columnSpacing(value) {\n // Clamp the spacing to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the spacing does not change\n if (this._columnSpacing === value) {\n return;\n }\n // Update the internal spacing.\n this._columnSpacing = value;\n // Schedule a fit of the parent.\n if (this.parent) {\n this.parent.fit();\n }\n }\n /**\n * Get the stretch factor for a specific row.\n *\n * @param index - The row index of interest.\n *\n * @returns The stretch factor for the row.\n *\n * #### Notes\n * This returns `-1` if the index is out of range.\n */\n rowStretch(index) {\n let sizer = this._rowSizers[index];\n return sizer ? sizer.stretch : -1;\n }\n /**\n * Set the stretch factor for a specific row.\n *\n * @param index - The row index of interest.\n *\n * @param value - The stretch factor for the row.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n setRowStretch(index, value) {\n // Look up the row sizer.\n let sizer = this._rowSizers[index];\n // Bail if the index is out of range.\n if (!sizer) {\n return;\n }\n // Clamp the value to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the stretch does not change.\n if (sizer.stretch === value) {\n return;\n }\n // Update the sizer stretch.\n sizer.stretch = value;\n // Schedule an update of the parent.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Get the stretch factor for a specific column.\n *\n * @param index - The column index of interest.\n *\n * @returns The stretch factor for the column.\n *\n * #### Notes\n * This returns `-1` if the index is out of range.\n */\n columnStretch(index) {\n let sizer = this._columnSizers[index];\n return sizer ? sizer.stretch : -1;\n }\n /**\n * Set the stretch factor for a specific column.\n *\n * @param index - The column index of interest.\n *\n * @param value - The stretch factor for the column.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n setColumnStretch(index, value) {\n // Look up the column sizer.\n let sizer = this._columnSizers[index];\n // Bail if the index is out of range.\n if (!sizer) {\n return;\n }\n // Clamp the value to the allowed range.\n value = Private$4.clampValue(value);\n // Bail if the stretch does not change.\n if (sizer.stretch === value) {\n return;\n }\n // Update the sizer stretch.\n sizer.stretch = value;\n // Schedule an update of the parent.\n if (this.parent) {\n this.parent.update();\n }\n }\n /**\n * Create an iterator over the widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n */\n *[Symbol.iterator]() {\n for (const item of this._items) {\n yield item.widget;\n }\n }\n /**\n * Add a widget to the grid layout.\n *\n * @param widget - The widget to add to the layout.\n *\n * #### Notes\n * If the widget is already contained in the layout, this is no-op.\n */\n addWidget(widget) {\n // Look up the index for the widget.\n let i = ArrayExt.findFirstIndex(this._items, it => it.widget === widget);\n // Bail if the widget is already in the layout.\n if (i !== -1) {\n return;\n }\n // Add the widget to the layout.\n this._items.push(new LayoutItem(widget));\n // Attach the widget to the parent.\n if (this.parent) {\n this.attachWidget(widget);\n }\n }\n /**\n * Remove a widget from the grid layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n // Look up the index for the widget.\n let i = ArrayExt.findFirstIndex(this._items, it => it.widget === widget);\n // Bail if the widget is not in the layout.\n if (i === -1) {\n return;\n }\n // Remove the widget from the layout.\n let item = ArrayExt.removeAt(this._items, i);\n // Detach the widget from the parent.\n if (this.parent) {\n this.detachWidget(widget);\n }\n // Dispose the layout item.\n item.dispose();\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n super.init();\n for (const widget of this) {\n this.attachWidget(widget);\n }\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param widget - The widget to attach to the parent.\n */\n attachWidget(widget) {\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param widget - The widget to detach from the parent.\n */\n detachWidget(widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Reset the min sizes of the sizers.\n for (let i = 0, n = this.rowCount; i < n; ++i) {\n this._rowSizers[i].minSize = 0;\n }\n for (let i = 0, n = this.columnCount; i < n; ++i) {\n this._columnSizers[i].minSize = 0;\n }\n // Filter for the visible layout items.\n let items = this._items.filter(it => !it.isHidden);\n // Fit the layout items.\n for (let i = 0, n = items.length; i < n; ++i) {\n items[i].fit();\n }\n // Get the max row and column index.\n let maxRow = this.rowCount - 1;\n let maxCol = this.columnCount - 1;\n // Sort the items by row span.\n items.sort(Private$4.rowSpanCmp);\n // Update the min sizes of the row sizers.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Fetch the item.\n let item = items[i];\n // Get the row bounds for the item.\n let config = GridLayout.getCellConfig(item.widget);\n let r1 = Math.min(config.row, maxRow);\n let r2 = Math.min(config.row + config.rowSpan - 1, maxRow);\n // Distribute the minimum height to the sizers as needed.\n Private$4.distributeMin(this._rowSizers, r1, r2, item.minHeight);\n }\n // Sort the items by column span.\n items.sort(Private$4.columnSpanCmp);\n // Update the min sizes of the column sizers.\n for (let i = 0, n = items.length; i < n; ++i) {\n // Fetch the item.\n let item = items[i];\n // Get the column bounds for the item.\n let config = GridLayout.getCellConfig(item.widget);\n let c1 = Math.min(config.column, maxCol);\n let c2 = Math.min(config.column + config.columnSpan - 1, maxCol);\n // Distribute the minimum width to the sizers as needed.\n Private$4.distributeMin(this._columnSizers, c1, c2, item.minWidth);\n }\n // If no size constraint is needed, just update the parent.\n if (this.fitPolicy === 'set-no-constraint') {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n return;\n }\n // Set up the computed min size.\n let minH = maxRow * this._rowSpacing;\n let minW = maxCol * this._columnSpacing;\n // Add the sizer minimums to the computed min size.\n for (let i = 0, n = this.rowCount; i < n; ++i) {\n minH += this._rowSizers[i].minSize;\n }\n for (let i = 0, n = this.columnCount; i < n; ++i) {\n minW += this._columnSizers[i].minSize;\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the layout area adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Get the max row and column index.\n let maxRow = this.rowCount - 1;\n let maxCol = this.columnCount - 1;\n // Compute the total fixed row and column space.\n let fixedRowSpace = maxRow * this._rowSpacing;\n let fixedColSpace = maxCol * this._columnSpacing;\n // Distribute the available space to the box sizers.\n BoxEngine.calc(this._rowSizers, Math.max(0, height - fixedRowSpace));\n BoxEngine.calc(this._columnSizers, Math.max(0, width - fixedColSpace));\n // Update the row start positions.\n for (let i = 0, pos = top, n = this.rowCount; i < n; ++i) {\n this._rowStarts[i] = pos;\n pos += this._rowSizers[i].size + this._rowSpacing;\n }\n // Update the column start positions.\n for (let i = 0, pos = left, n = this.columnCount; i < n; ++i) {\n this._columnStarts[i] = pos;\n pos += this._columnSizers[i].size + this._columnSpacing;\n }\n // Update the geometry of the layout items.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Fetch the cell bounds for the widget.\n let config = GridLayout.getCellConfig(item.widget);\n let r1 = Math.min(config.row, maxRow);\n let c1 = Math.min(config.column, maxCol);\n let r2 = Math.min(config.row + config.rowSpan - 1, maxRow);\n let c2 = Math.min(config.column + config.columnSpan - 1, maxCol);\n // Compute the cell geometry.\n let x = this._columnStarts[c1];\n let y = this._rowStarts[r1];\n let w = this._columnStarts[c2] + this._columnSizers[c2].size - x;\n let h = this._rowStarts[r2] + this._rowSizers[r2].size - y;\n // Update the geometry of the layout item.\n item.update(x, y, w, h);\n }\n }\n}\n/**\n * The namespace for the `GridLayout` class statics.\n */\n(function (GridLayout) {\n /**\n * Get the cell config for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @returns The cell config for the widget.\n */\n function getCellConfig(widget) {\n return Private$4.cellConfigProperty.get(widget);\n }\n GridLayout.getCellConfig = getCellConfig;\n /**\n * Set the cell config for the given widget.\n *\n * @param widget - The widget of interest.\n *\n * @param value - The value for the cell config.\n */\n function setCellConfig(widget, value) {\n Private$4.cellConfigProperty.set(widget, Private$4.normalizeConfig(value));\n }\n GridLayout.setCellConfig = setCellConfig;\n})(GridLayout || (GridLayout = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$4;\n(function (Private) {\n /**\n * The property descriptor for the widget cell config.\n */\n Private.cellConfigProperty = new AttachedProperty({\n name: 'cellConfig',\n create: () => ({ row: 0, column: 0, rowSpan: 1, columnSpan: 1 }),\n changed: onChildCellConfigChanged\n });\n /**\n * Normalize a partial cell config object.\n */\n function normalizeConfig(config) {\n let row = Math.max(0, Math.floor(config.row || 0));\n let column = Math.max(0, Math.floor(config.column || 0));\n let rowSpan = Math.max(1, Math.floor(config.rowSpan || 0));\n let columnSpan = Math.max(1, Math.floor(config.columnSpan || 0));\n return { row, column, rowSpan, columnSpan };\n }\n Private.normalizeConfig = normalizeConfig;\n /**\n * Clamp a value to an integer >= 0.\n */\n function clampValue(value) {\n return Math.max(0, Math.floor(value));\n }\n Private.clampValue = clampValue;\n /**\n * A sort comparison function for row spans.\n */\n function rowSpanCmp(a, b) {\n let c1 = Private.cellConfigProperty.get(a.widget);\n let c2 = Private.cellConfigProperty.get(b.widget);\n return c1.rowSpan - c2.rowSpan;\n }\n Private.rowSpanCmp = rowSpanCmp;\n /**\n * A sort comparison function for column spans.\n */\n function columnSpanCmp(a, b) {\n let c1 = Private.cellConfigProperty.get(a.widget);\n let c2 = Private.cellConfigProperty.get(b.widget);\n return c1.columnSpan - c2.columnSpan;\n }\n Private.columnSpanCmp = columnSpanCmp;\n /**\n * Reallocate the box sizers for the given grid dimensions.\n */\n function reallocSizers(sizers, count) {\n // Coerce the count to the valid range.\n count = Math.max(1, Math.floor(count));\n // Add the missing sizers.\n while (sizers.length < count) {\n sizers.push(new BoxSizer());\n }\n // Remove the extra sizers.\n if (sizers.length > count) {\n sizers.length = count;\n }\n }\n Private.reallocSizers = reallocSizers;\n /**\n * Distribute a min size constraint across a range of sizers.\n */\n function distributeMin(sizers, i1, i2, minSize) {\n // Sanity check the indices.\n if (i2 < i1) {\n return;\n }\n // Handle the simple case of no cell span.\n if (i1 === i2) {\n let sizer = sizers[i1];\n sizer.minSize = Math.max(sizer.minSize, minSize);\n return;\n }\n // Compute the total current min size of the span.\n let totalMin = 0;\n for (let i = i1; i <= i2; ++i) {\n totalMin += sizers[i].minSize;\n }\n // Do nothing if the total is greater than the required.\n if (totalMin >= minSize) {\n return;\n }\n // Compute the portion of the space to allocate to each sizer.\n let portion = (minSize - totalMin) / (i2 - i1 + 1);\n // Add the portion to each sizer.\n for (let i = i1; i <= i2; ++i) {\n sizers[i].minSize += portion;\n }\n }\n Private.distributeMin = distributeMin;\n /**\n * The change handler for the child cell config property.\n */\n function onChildCellConfigChanged(child) {\n if (child.parent && child.parent.layout instanceof GridLayout) {\n child.parent.fit();\n }\n }\n})(Private$4 || (Private$4 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which displays menus as a canonical menu bar.\n */\nclass MenuBar extends Widget {\n /**\n * Construct a new menu bar.\n *\n * @param options - The options for initializing the menu bar.\n */\n constructor(options = {}) {\n super({ node: Private$3.createNode() });\n // Track the index of the item that is currently focused or hovered. -1 means nothing focused or hovered.\n this._activeIndex = -1;\n // Track which item can be focused using the TAB key. Unlike _activeIndex will\n // always point to a menuitem. Whenever you update this value, it's important\n // to follow it with an \"update-request\" message so that the `tabindex`\n // attribute on each menubar item gets properly updated.\n this._tabFocusIndex = 0;\n this._menus = [];\n this._childMenu = null;\n this._overflowMenu = null;\n this._menuItemSizes = [];\n this._overflowIndex = -1;\n this.addClass('lm-MenuBar');\n this.setFlag(Widget.Flag.DisallowLayout);\n this.renderer = options.renderer || MenuBar.defaultRenderer;\n this._forceItemsPosition = options.forceItemsPosition || {\n forceX: true,\n forceY: true\n };\n this._overflowMenuOptions = options.overflowMenuOptions || {\n isVisible: true\n };\n }\n /**\n * Dispose of the resources held by the widget.\n */\n dispose() {\n this._closeChildMenu();\n this._menus.length = 0;\n super.dispose();\n }\n /**\n * The child menu of the menu bar.\n *\n * #### Notes\n * This will be `null` if the menu bar does not have an open menu.\n */\n get childMenu() {\n return this._childMenu;\n }\n /**\n * The overflow index of the menu bar.\n */\n get overflowIndex() {\n return this._overflowIndex;\n }\n /**\n * The overflow menu of the menu bar.\n */\n get overflowMenu() {\n return this._overflowMenu;\n }\n /**\n * Get the menu bar content node.\n *\n * #### Notes\n * This is the node which holds the menu title nodes.\n *\n * Modifying this node directly can lead to undefined behavior.\n */\n get contentNode() {\n return this.node.getElementsByClassName('lm-MenuBar-content')[0];\n }\n /**\n * Get the currently active menu.\n */\n get activeMenu() {\n return this._menus[this._activeIndex] || null;\n }\n /**\n * Set the currently active menu.\n *\n * #### Notes\n * If the menu does not exist, the menu will be set to `null`.\n */\n set activeMenu(value) {\n this.activeIndex = value ? this._menus.indexOf(value) : -1;\n }\n /**\n * Get the index of the currently active menu.\n *\n * #### Notes\n * This will be `-1` if no menu is active.\n */\n get activeIndex() {\n return this._activeIndex;\n }\n /**\n * Set the index of the currently active menu.\n *\n * #### Notes\n * If the menu cannot be activated, the index will be set to `-1`.\n */\n set activeIndex(value) {\n // Adjust the value for an out of range index.\n if (value < 0 || value >= this._menus.length) {\n value = -1;\n }\n // An empty menu cannot be active\n if (value > -1 && this._menus[value].items.length === 0) {\n value = -1;\n }\n // Bail early if the index will not change.\n if (this._activeIndex === value) {\n return;\n }\n // Update the active index.\n this._activeIndex = value;\n // Schedule an update of the items.\n this.update();\n }\n /**\n * A read-only array of the menus in the menu bar.\n */\n get menus() {\n return this._menus;\n }\n /**\n * Open the active menu and activate its first menu item.\n *\n * #### Notes\n * If there is no active menu, this is a no-op.\n */\n openActiveMenu() {\n // Bail early if there is no active item.\n if (this._activeIndex === -1) {\n return;\n }\n // Open the child menu.\n this._openChildMenu();\n // Activate the first item in the child menu.\n if (this._childMenu) {\n this._childMenu.activeIndex = -1;\n this._childMenu.activateNextItem();\n }\n }\n /**\n * Add a menu to the end of the menu bar.\n *\n * @param menu - The menu to add to the menu bar.\n *\n * #### Notes\n * If the menu is already added to the menu bar, it will be moved.\n */\n addMenu(menu, update = true) {\n this.insertMenu(this._menus.length, menu, update);\n }\n /**\n * Insert a menu into the menu bar at the specified index.\n *\n * @param index - The index at which to insert the menu.\n *\n * @param menu - The menu to insert into the menu bar.\n *\n * #### Notes\n * The index will be clamped to the bounds of the menus.\n *\n * If the menu is already added to the menu bar, it will be moved.\n */\n insertMenu(index, menu, update = true) {\n // Close the child menu before making changes.\n this._closeChildMenu();\n // Look up the index of the menu.\n let i = this._menus.indexOf(menu);\n // Clamp the insert index to the array bounds.\n let j = Math.max(0, Math.min(index, this._menus.length));\n // If the menu is not in the array, insert it.\n if (i === -1) {\n // Insert the menu into the array.\n ArrayExt.insert(this._menus, j, menu);\n // Add the styling class to the menu.\n menu.addClass('lm-MenuBar-menu');\n // Connect to the menu signals.\n menu.aboutToClose.connect(this._onMenuAboutToClose, this);\n menu.menuRequested.connect(this._onMenuMenuRequested, this);\n menu.title.changed.connect(this._onTitleChanged, this);\n // Schedule an update of the items.\n if (update) {\n this.update();\n }\n // There is nothing more to do.\n return;\n }\n // Otherwise, the menu exists in the array and should be moved.\n // Adjust the index if the location is at the end of the array.\n if (j === this._menus.length) {\n j--;\n }\n // Bail if there is no effective move.\n if (i === j) {\n return;\n }\n // Move the menu to the new locations.\n ArrayExt.move(this._menus, i, j);\n // Schedule an update of the items.\n if (update) {\n this.update();\n }\n }\n /**\n * Remove a menu from the menu bar.\n *\n * @param menu - The menu to remove from the menu bar.\n *\n * #### Notes\n * This is a no-op if the menu is not in the menu bar.\n */\n removeMenu(menu, update = true) {\n this.removeMenuAt(this._menus.indexOf(menu), update);\n }\n /**\n * Remove the menu at a given index from the menu bar.\n *\n * @param index - The index of the menu to remove.\n *\n * #### Notes\n * This is a no-op if the index is out of range.\n */\n removeMenuAt(index, update = true) {\n // Close the child menu before making changes.\n this._closeChildMenu();\n // Remove the menu from the array.\n let menu = ArrayExt.removeAt(this._menus, index);\n // Bail if the index is out of range.\n if (!menu) {\n return;\n }\n // Disconnect from the menu signals.\n menu.aboutToClose.disconnect(this._onMenuAboutToClose, this);\n menu.menuRequested.disconnect(this._onMenuMenuRequested, this);\n menu.title.changed.disconnect(this._onTitleChanged, this);\n // Remove the styling class from the menu.\n menu.removeClass('lm-MenuBar-menu');\n // Schedule an update of the items.\n if (update) {\n this.update();\n }\n }\n /**\n * Remove all menus from the menu bar.\n */\n clearMenus() {\n // Bail if there is nothing to remove.\n if (this._menus.length === 0) {\n return;\n }\n // Close the child menu before making changes.\n this._closeChildMenu();\n // Disconnect from the menu signals and remove the styling class.\n for (let menu of this._menus) {\n menu.aboutToClose.disconnect(this._onMenuAboutToClose, this);\n menu.menuRequested.disconnect(this._onMenuMenuRequested, this);\n menu.title.changed.disconnect(this._onTitleChanged, this);\n menu.removeClass('lm-MenuBar-menu');\n }\n // Clear the menus array.\n this._menus.length = 0;\n // Schedule an update of the items.\n this.update();\n }\n /**\n * Handle the DOM events for the menu bar.\n *\n * @param event - The DOM event sent to the menu bar.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the menu bar's DOM nodes. It\n * should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'mousedown':\n this._evtMouseDown(event);\n break;\n case 'mousemove':\n this._evtMouseMove(event);\n break;\n case 'focusout':\n this._evtFocusOut(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('keydown', this);\n this.node.addEventListener('mousedown', this);\n this.node.addEventListener('mousemove', this);\n this.node.addEventListener('focusout', this);\n this.node.addEventListener('contextmenu', this);\n }\n /**\n * A message handler invoked on an `'after-detach'` message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('keydown', this);\n this.node.removeEventListener('mousedown', this);\n this.node.removeEventListener('mousemove', this);\n this.node.removeEventListener('focusout', this);\n this.node.removeEventListener('contextmenu', this);\n this._closeChildMenu();\n }\n /**\n * A message handler invoked on an `'activate-request'` message.\n */\n onActivateRequest(msg) {\n if (this.isAttached) {\n this._focusItemAt(0);\n }\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n this.update();\n super.onResize(msg);\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n var _a;\n let menus = this._menus;\n let renderer = this.renderer;\n let activeIndex = this._activeIndex;\n let tabFocusIndex = this._tabFocusIndex >= 0 && this._tabFocusIndex < menus.length\n ? this._tabFocusIndex\n : 0;\n let length = this._overflowIndex > -1 ? this._overflowIndex : menus.length;\n let totalMenuSize = 0;\n let isVisible = false;\n // Check that the overflow menu doesn't count\n length = this._overflowMenu !== null ? length - 1 : length;\n let content = new Array(length);\n // Render visible menus\n for (let i = 0; i < length; ++i) {\n content[i] = renderer.renderItem({\n title: menus[i].title,\n active: i === activeIndex,\n tabbable: i === tabFocusIndex,\n disabled: menus[i].items.length === 0,\n onfocus: () => {\n this._tabFocusIndex = i;\n this.activeIndex = i;\n }\n });\n // Calculate size of current menu\n totalMenuSize += this._menuItemSizes[i];\n // Check if overflow menu is already rendered\n if (menus[i].title.label === this._overflowMenuOptions.title) {\n isVisible = true;\n length--;\n }\n }\n // Render overflow menu if needed and active\n if (this._overflowMenuOptions.isVisible) {\n if (this._overflowIndex > -1 && !isVisible) {\n // Create overflow menu\n if (this._overflowMenu === null) {\n const overflowMenuTitle = (_a = this._overflowMenuOptions.title) !== null && _a !== void 0 ? _a : '...';\n this._overflowMenu = new Menu({ commands: new CommandRegistry() });\n this._overflowMenu.title.label = overflowMenuTitle;\n this._overflowMenu.title.mnemonic = 0;\n this.addMenu(this._overflowMenu, false);\n }\n // Move menus to overflow menu\n for (let i = menus.length - 2; i >= length; i--) {\n const submenu = this.menus[i];\n submenu.title.mnemonic = 0;\n this._overflowMenu.insertItem(0, {\n type: 'submenu',\n submenu: submenu\n });\n this.removeMenu(submenu, false);\n }\n content[length] = renderer.renderItem({\n title: this._overflowMenu.title,\n active: length === activeIndex && menus[length].items.length !== 0,\n tabbable: length === tabFocusIndex,\n disabled: menus[length].items.length === 0,\n onfocus: () => {\n this._tabFocusIndex = length;\n this.activeIndex = length;\n }\n });\n length++;\n }\n else if (this._overflowMenu !== null) {\n // Remove submenus from overflow menu\n let overflowMenuItems = this._overflowMenu.items;\n let screenSize = this.node.offsetWidth;\n let n = this._overflowMenu.items.length;\n for (let i = 0; i < n; ++i) {\n let index = menus.length - 1 - i;\n if (screenSize - totalMenuSize > this._menuItemSizes[index]) {\n let menu = overflowMenuItems[0].submenu;\n this._overflowMenu.removeItemAt(0);\n this.insertMenu(length, menu, false);\n content[length] = renderer.renderItem({\n title: menu.title,\n active: false,\n tabbable: length === tabFocusIndex,\n disabled: menus[length].items.length === 0,\n onfocus: () => {\n this._tabFocusIndex = length;\n this.activeIndex = length;\n }\n });\n length++;\n }\n }\n if (this._overflowMenu.items.length === 0) {\n this.removeMenu(this._overflowMenu, false);\n content.pop();\n this._overflowMenu = null;\n this._overflowIndex = -1;\n }\n }\n }\n VirtualDOM.render(content, this.contentNode);\n this._updateOverflowIndex();\n }\n /**\n * Calculate and update the current overflow index.\n */\n _updateOverflowIndex() {\n if (!this._overflowMenuOptions.isVisible) {\n return;\n }\n // Get elements visible in the main menu bar\n const itemMenus = this.contentNode.childNodes;\n let screenSize = this.node.offsetWidth;\n let totalMenuSize = 0;\n let index = -1;\n let n = itemMenus.length;\n if (this._menuItemSizes.length == 0) {\n // Check if it is the first resize and get info about menu items sizes\n for (let i = 0; i < n; i++) {\n let item = itemMenus[i];\n // Add sizes to array\n totalMenuSize += item.offsetWidth;\n this._menuItemSizes.push(item.offsetWidth);\n if (totalMenuSize > screenSize && index === -1) {\n index = i;\n }\n }\n }\n else {\n // Calculate current menu size\n for (let i = 0; i < this._menuItemSizes.length; i++) {\n totalMenuSize += this._menuItemSizes[i];\n if (totalMenuSize > screenSize) {\n index = i;\n break;\n }\n }\n }\n this._overflowIndex = index;\n }\n /**\n * Handle the `'keydown'` event for the menu bar.\n *\n * #### Notes\n * All keys are trapped except the tab key that is ignored.\n */\n _evtKeyDown(event) {\n // Fetch the key code for the event.\n let kc = event.keyCode;\n // Reset the active index on tab, but do not trap the tab key.\n if (kc === 9) {\n this.activeIndex = -1;\n return;\n }\n // A menu bar handles all other keydown events.\n event.preventDefault();\n event.stopPropagation();\n // Enter, Space, Up Arrow, Down Arrow\n if (kc === 13 || kc === 32 || kc === 38 || kc === 40) {\n // The active index may have changed (for example, user hovers over an\n // item with the mouse), so be sure to use the focus index.\n this.activeIndex = this._tabFocusIndex;\n if (this.activeIndex !== this._tabFocusIndex) {\n // Bail if the setter refused to set activeIndex to tabFocusIndex\n // because it means that the item at tabFocusIndex cannot be opened (for\n // example, it has an empty menu)\n return;\n }\n this.openActiveMenu();\n return;\n }\n // Escape\n if (kc === 27) {\n this._closeChildMenu();\n this._focusItemAt(this.activeIndex);\n return;\n }\n // Left or Right Arrow\n if (kc === 37 || kc === 39) {\n let direction = kc === 37 ? -1 : 1;\n let start = this._tabFocusIndex + direction;\n let n = this._menus.length;\n for (let i = 0; i < n; i++) {\n let index = (n + start + direction * i) % n;\n if (this._menus[index].items.length) {\n this._focusItemAt(index);\n return;\n }\n }\n return;\n }\n // Get the pressed key character.\n let key = getKeyboardLayout().keyForKeydownEvent(event);\n // Bail if the key is not valid.\n if (!key) {\n return;\n }\n // Search for the next best matching mnemonic item.\n let start = this._activeIndex + 1;\n let result = Private$3.findMnemonic(this._menus, key, start);\n // Handle the requested mnemonic based on the search results.\n // If exactly one mnemonic is matched, that menu is opened.\n // Otherwise, the next mnemonic is activated if available,\n // followed by the auto mnemonic if available.\n if (result.index !== -1 && !result.multiple) {\n this.activeIndex = result.index;\n this.openActiveMenu();\n }\n else if (result.index !== -1) {\n this.activeIndex = result.index;\n this._focusItemAt(this.activeIndex);\n }\n else if (result.auto !== -1) {\n this.activeIndex = result.auto;\n this._focusItemAt(this.activeIndex);\n }\n }\n /**\n * Handle the `'mousedown'` event for the menu bar.\n */\n _evtMouseDown(event) {\n // Bail if the mouse press was not on the menu bar. This can occur\n // when the document listener is installed for an active menu bar.\n if (!ElementExt.hitTest(this.node, event.clientX, event.clientY)) {\n return;\n }\n // Stop the propagation of the event. Immediate propagation is\n // also stopped so that an open menu does not handle the event.\n event.stopPropagation();\n event.stopImmediatePropagation();\n // Check if the mouse is over one of the menu items.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return ElementExt.hitTest(node, event.clientX, event.clientY);\n });\n // If the press was not on an item, close the child menu.\n if (index === -1) {\n this._closeChildMenu();\n return;\n }\n // If the press was not the left mouse button, do nothing further.\n if (event.button !== 0) {\n return;\n }\n // Otherwise, toggle the open state of the child menu.\n if (this._childMenu) {\n this._closeChildMenu();\n this.activeIndex = index;\n }\n else {\n // If we don't call preventDefault() here, then the item in the menu\n // bar will take focus over the menu that is being opened.\n event.preventDefault();\n const position = this._positionForMenu(index);\n Menu.saveWindowData();\n // Begin DOM modifications.\n this.activeIndex = index;\n this._openChildMenu(position);\n }\n }\n /**\n * Handle the `'mousemove'` event for the menu bar.\n */\n _evtMouseMove(event) {\n // Check if the mouse is over one of the menu items.\n let index = ArrayExt.findFirstIndex(this.contentNode.children, node => {\n return ElementExt.hitTest(node, event.clientX, event.clientY);\n });\n // Bail early if the active index will not change.\n if (index === this._activeIndex) {\n return;\n }\n // Bail early if a child menu is open and the mouse is not over\n // an item. This allows the child menu to be kept open when the\n // mouse is over the empty part of the menu bar.\n if (index === -1 && this._childMenu) {\n return;\n }\n // Get position for the new menu >before< updating active index.\n const position = index >= 0 && this._childMenu ? this._positionForMenu(index) : null;\n // Before any modification, update window data.\n Menu.saveWindowData();\n // Begin DOM modifications.\n // Update the active index to the hovered item.\n this.activeIndex = index;\n // Open the new menu if a menu is already open.\n if (position) {\n this._openChildMenu(position);\n }\n }\n /**\n * Find initial position for the menu based on menubar item position.\n *\n * NOTE: this should be called before updating active index to avoid\n * an additional layout and style invalidation as changing active\n * index modifies DOM.\n */\n _positionForMenu(index) {\n let itemNode = this.contentNode.children[index];\n let { left, bottom } = itemNode.getBoundingClientRect();\n return {\n top: bottom,\n left\n };\n }\n /**\n * Handle the `'focusout'` event for the menu bar.\n */\n _evtFocusOut(event) {\n // Reset the active index if there is no open menu and the menubar is losing focus.\n if (!this._childMenu && !this.node.contains(event.relatedTarget)) {\n this.activeIndex = -1;\n }\n }\n /**\n * Focus an item in the menu bar.\n *\n * #### Notes\n * Does not open the associated menu.\n */\n _focusItemAt(index) {\n const itemNode = this.contentNode.childNodes[index];\n if (itemNode) {\n itemNode.focus();\n }\n }\n /**\n * Open the child menu at the active index immediately.\n *\n * If a different child menu is already open, it will be closed,\n * even if there is no active menu.\n */\n _openChildMenu(options = {}) {\n // If there is no active menu, close the current menu.\n let newMenu = this.activeMenu;\n if (!newMenu) {\n this._closeChildMenu();\n return;\n }\n // Bail if there is no effective menu change.\n let oldMenu = this._childMenu;\n if (oldMenu === newMenu) {\n return;\n }\n // Swap the internal menu reference.\n this._childMenu = newMenu;\n // Close the current menu, or setup for the new menu.\n if (oldMenu) {\n oldMenu.close();\n }\n else {\n document.addEventListener('mousedown', this, true);\n }\n // Update the tab focus index and ensure the menu bar is updated.\n this._tabFocusIndex = this.activeIndex;\n MessageLoop.sendMessage(this, Widget.Msg.UpdateRequest);\n // Get the positioning data for the new menu.\n let { left, top } = options;\n if (typeof left === 'undefined' || typeof top === 'undefined') {\n ({ left, top } = this._positionForMenu(this._activeIndex));\n }\n // Begin DOM modifications\n if (!oldMenu) {\n // Continue setup for new menu\n this.addClass('lm-mod-active');\n }\n // Open the new menu at the computed location.\n if (newMenu.items.length > 0) {\n newMenu.open(left, top, this._forceItemsPosition);\n }\n }\n /**\n * Close the child menu immediately.\n *\n * This is a no-op if a child menu is not open.\n */\n _closeChildMenu() {\n // Bail if no child menu is open.\n if (!this._childMenu) {\n return;\n }\n // Remove the active class from the menu bar.\n this.removeClass('lm-mod-active');\n // Remove the document listeners.\n document.removeEventListener('mousedown', this, true);\n // Clear the internal menu reference.\n let menu = this._childMenu;\n this._childMenu = null;\n // Close the menu.\n menu.close();\n // Reset the active index.\n this.activeIndex = -1;\n }\n /**\n * Handle the `aboutToClose` signal of a menu.\n */\n _onMenuAboutToClose(sender) {\n // Bail if the sender is not the child menu.\n if (sender !== this._childMenu) {\n return;\n }\n // Remove the active class from the menu bar.\n this.removeClass('lm-mod-active');\n // Remove the document listeners.\n document.removeEventListener('mousedown', this, true);\n // Clear the internal menu reference.\n this._childMenu = null;\n // Reset the active index.\n this.activeIndex = -1;\n }\n /**\n * Handle the `menuRequested` signal of a child menu.\n */\n _onMenuMenuRequested(sender, args) {\n // Bail if the sender is not the child menu.\n if (sender !== this._childMenu) {\n return;\n }\n // Look up the active index and menu count.\n let i = this._activeIndex;\n let n = this._menus.length;\n // Active the next requested index.\n switch (args) {\n case 'next':\n this.activeIndex = i === n - 1 ? 0 : i + 1;\n break;\n case 'previous':\n this.activeIndex = i === 0 ? n - 1 : i - 1;\n break;\n }\n // Open the active menu.\n this.openActiveMenu();\n }\n /**\n * Handle the `changed` signal of a title object.\n */\n _onTitleChanged() {\n this.update();\n }\n}\n/**\n * The namespace for the `MenuBar` class statics.\n */\n(function (MenuBar) {\n /**\n * The default implementation of `IRenderer`.\n *\n * #### Notes\n * Subclasses are free to reimplement rendering methods as needed.\n */\n class Renderer {\n /**\n * Render the virtual element for a menu bar item.\n *\n * @param data - The data to use for rendering the item.\n *\n * @returns A virtual element representing the item.\n */\n renderItem(data) {\n let className = this.createItemClass(data);\n let dataset = this.createItemDataset(data);\n let aria = this.createItemARIA(data);\n return h.li({\n className,\n dataset,\n ...(data.disabled ? {} : { tabindex: data.tabbable ? '0' : '-1' }),\n onfocus: data.onfocus,\n ...aria\n }, this.renderIcon(data), this.renderLabel(data));\n }\n /**\n * Render the icon element for a menu bar item.\n *\n * @param data - The data to use for rendering the icon.\n *\n * @returns A virtual element representing the item icon.\n */\n renderIcon(data) {\n let className = this.createIconClass(data);\n // If data.title.icon is undefined, it will be ignored.\n return h.div({ className }, data.title.icon, data.title.iconLabel);\n }\n /**\n * Render the label element for a menu item.\n *\n * @param data - The data to use for rendering the label.\n *\n * @returns A virtual element representing the item label.\n */\n renderLabel(data) {\n let content = this.formatLabel(data);\n return h.div({ className: 'lm-MenuBar-itemLabel' }, content);\n }\n /**\n * Create the class name for the menu bar item.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the menu item.\n */\n createItemClass(data) {\n let name = 'lm-MenuBar-item';\n if (data.title.className) {\n name += ` ${data.title.className}`;\n }\n if (data.active && !data.disabled) {\n name += ' lm-mod-active';\n }\n return name;\n }\n /**\n * Create the dataset for a menu bar item.\n *\n * @param data - The data to use for the item.\n *\n * @returns The dataset for the menu bar item.\n */\n createItemDataset(data) {\n return data.title.dataset;\n }\n /**\n * Create the aria attributes for menu bar item.\n *\n * @param data - The data to use for the aria attributes.\n *\n * @returns The aria attributes object for the item.\n */\n createItemARIA(data) {\n return {\n role: 'menuitem',\n 'aria-haspopup': 'true',\n 'aria-disabled': data.disabled ? 'true' : 'false'\n };\n }\n /**\n * Create the class name for the menu bar item icon.\n *\n * @param data - The data to use for the class name.\n *\n * @returns The full class name for the item icon.\n */\n createIconClass(data) {\n let name = 'lm-MenuBar-itemIcon';\n let extra = data.title.iconClass;\n return extra ? `${name} ${extra}` : name;\n }\n /**\n * Create the render content for the label node.\n *\n * @param data - The data to use for the label content.\n *\n * @returns The content to add to the label node.\n */\n formatLabel(data) {\n // Fetch the label text and mnemonic index.\n let { label, mnemonic } = data.title;\n // If the index is out of range, do not modify the label.\n if (mnemonic < 0 || mnemonic >= label.length) {\n return label;\n }\n // Split the label into parts.\n let prefix = label.slice(0, mnemonic);\n let suffix = label.slice(mnemonic + 1);\n let char = label[mnemonic];\n // Wrap the mnemonic character in a span.\n let span = h.span({ className: 'lm-MenuBar-itemMnemonic' }, char);\n // Return the content parts.\n return [prefix, span, suffix];\n }\n }\n MenuBar.Renderer = Renderer;\n /**\n * The default `Renderer` instance.\n */\n MenuBar.defaultRenderer = new Renderer();\n})(MenuBar || (MenuBar = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$3;\n(function (Private) {\n /**\n * Create the DOM node for a menu bar.\n */\n function createNode() {\n let node = document.createElement('div');\n let content = document.createElement('ul');\n content.className = 'lm-MenuBar-content';\n node.appendChild(content);\n content.setAttribute('role', 'menubar');\n return node;\n }\n Private.createNode = createNode;\n /**\n * Find the best matching mnemonic item.\n *\n * The search starts at the given index and wraps around.\n */\n function findMnemonic(menus, key, start) {\n // Setup the result variables.\n let index = -1;\n let auto = -1;\n let multiple = false;\n // Normalize the key to upper case.\n let upperKey = key.toUpperCase();\n // Search the items from the given start index.\n for (let i = 0, n = menus.length; i < n; ++i) {\n // Compute the wrapped index.\n let k = (i + start) % n;\n // Look up the menu title.\n let title = menus[k].title;\n // Ignore titles with an empty label.\n if (title.label.length === 0) {\n continue;\n }\n // Look up the mnemonic index for the label.\n let mn = title.mnemonic;\n // Handle a valid mnemonic index.\n if (mn >= 0 && mn < title.label.length) {\n if (title.label[mn].toUpperCase() === upperKey) {\n if (index === -1) {\n index = k;\n }\n else {\n multiple = true;\n }\n }\n continue;\n }\n // Finally, handle the auto index if possible.\n if (auto === -1 && title.label[0].toUpperCase() === upperKey) {\n auto = k;\n }\n }\n // Return the search results.\n return { index, multiple, auto };\n }\n Private.findMnemonic = findMnemonic;\n})(Private$3 || (Private$3 = {}));\n\n/**\n * A widget which implements a canonical scroll bar.\n */\nclass ScrollBar extends Widget {\n /**\n * Construct a new scroll bar.\n *\n * @param options - The options for initializing the scroll bar.\n */\n constructor(options = {}) {\n super({ node: Private$2.createNode() });\n /**\n * A timeout callback for repeating the mouse press.\n */\n this._onRepeat = () => {\n // Clear the repeat timer id.\n this._repeatTimer = -1;\n // Bail if the mouse has been released.\n if (!this._pressData) {\n return;\n }\n // Look up the part that was pressed.\n let part = this._pressData.part;\n // Bail if the thumb was pressed.\n if (part === 'thumb') {\n return;\n }\n // Schedule the timer for another repeat.\n this._repeatTimer = window.setTimeout(this._onRepeat, 20);\n // Get the current mouse position.\n let mouseX = this._pressData.mouseX;\n let mouseY = this._pressData.mouseY;\n // Handle a decrement button repeat.\n if (part === 'decrement') {\n // Bail if the mouse is not over the button.\n if (!ElementExt.hitTest(this.decrementNode, mouseX, mouseY)) {\n return;\n }\n // Emit the step requested signal.\n this._stepRequested.emit('decrement');\n // Finished.\n return;\n }\n // Handle an increment button repeat.\n if (part === 'increment') {\n // Bail if the mouse is not over the button.\n if (!ElementExt.hitTest(this.incrementNode, mouseX, mouseY)) {\n return;\n }\n // Emit the step requested signal.\n this._stepRequested.emit('increment');\n // Finished.\n return;\n }\n // Handle a track repeat.\n if (part === 'track') {\n // Bail if the mouse is not over the track.\n if (!ElementExt.hitTest(this.trackNode, mouseX, mouseY)) {\n return;\n }\n // Fetch the thumb node.\n let thumbNode = this.thumbNode;\n // Bail if the mouse is over the thumb.\n if (ElementExt.hitTest(thumbNode, mouseX, mouseY)) {\n return;\n }\n // Fetch the client rect for the thumb.\n let thumbRect = thumbNode.getBoundingClientRect();\n // Determine the direction for the page request.\n let dir;\n if (this._orientation === 'horizontal') {\n dir = mouseX < thumbRect.left ? 'decrement' : 'increment';\n }\n else {\n dir = mouseY < thumbRect.top ? 'decrement' : 'increment';\n }\n // Emit the page requested signal.\n this._pageRequested.emit(dir);\n // Finished.\n return;\n }\n };\n this._value = 0;\n this._page = 10;\n this._maximum = 100;\n this._repeatTimer = -1;\n this._pressData = null;\n this._thumbMoved = new Signal(this);\n this._stepRequested = new Signal(this);\n this._pageRequested = new Signal(this);\n this.addClass('lm-ScrollBar');\n this.setFlag(Widget.Flag.DisallowLayout);\n // Set the orientation.\n this._orientation = options.orientation || 'vertical';\n this.dataset['orientation'] = this._orientation;\n // Parse the rest of the options.\n if (options.maximum !== undefined) {\n this._maximum = Math.max(0, options.maximum);\n }\n if (options.page !== undefined) {\n this._page = Math.max(0, options.page);\n }\n if (options.value !== undefined) {\n this._value = Math.max(0, Math.min(options.value, this._maximum));\n }\n }\n /**\n * A signal emitted when the user moves the scroll thumb.\n *\n * #### Notes\n * The payload is the current value of the scroll bar.\n */\n get thumbMoved() {\n return this._thumbMoved;\n }\n /**\n * A signal emitted when the user clicks a step button.\n *\n * #### Notes\n * The payload is whether a decrease or increase is requested.\n */\n get stepRequested() {\n return this._stepRequested;\n }\n /**\n * A signal emitted when the user clicks the scroll track.\n *\n * #### Notes\n * The payload is whether a decrease or increase is requested.\n */\n get pageRequested() {\n return this._pageRequested;\n }\n /**\n * Get the orientation of the scroll bar.\n */\n get orientation() {\n return this._orientation;\n }\n /**\n * Set the orientation of the scroll bar.\n */\n set orientation(value) {\n // Do nothing if the orientation does not change.\n if (this._orientation === value) {\n return;\n }\n // Release the mouse before making changes.\n this._releaseMouse();\n // Update the internal orientation.\n this._orientation = value;\n this.dataset['orientation'] = value;\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * Get the current value of the scroll bar.\n */\n get value() {\n return this._value;\n }\n /**\n * Set the current value of the scroll bar.\n *\n * #### Notes\n * The value will be clamped to the range `[0, maximum]`.\n */\n set value(value) {\n // Clamp the value to the allowable range.\n value = Math.max(0, Math.min(value, this._maximum));\n // Do nothing if the value does not change.\n if (this._value === value) {\n return;\n }\n // Update the internal value.\n this._value = value;\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * Get the page size of the scroll bar.\n *\n * #### Notes\n * The page size is the amount of visible content in the scrolled\n * region, expressed in data units. It determines the size of the\n * scroll bar thumb.\n */\n get page() {\n return this._page;\n }\n /**\n * Set the page size of the scroll bar.\n *\n * #### Notes\n * The page size will be clamped to the range `[0, Infinity]`.\n */\n set page(value) {\n // Clamp the page size to the allowable range.\n value = Math.max(0, value);\n // Do nothing if the value does not change.\n if (this._page === value) {\n return;\n }\n // Update the internal page size.\n this._page = value;\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * Get the maximum value of the scroll bar.\n */\n get maximum() {\n return this._maximum;\n }\n /**\n * Set the maximum value of the scroll bar.\n *\n * #### Notes\n * The max size will be clamped to the range `[0, Infinity]`.\n */\n set maximum(value) {\n // Clamp the value to the allowable range.\n value = Math.max(0, value);\n // Do nothing if the value does not change.\n if (this._maximum === value) {\n return;\n }\n // Update the internal values.\n this._maximum = value;\n // Clamp the current value to the new range.\n this._value = Math.min(this._value, value);\n // Schedule an update the scroll bar.\n this.update();\n }\n /**\n * The scroll bar decrement button node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get decrementNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-button')[0];\n }\n /**\n * The scroll bar increment button node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get incrementNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-button')[1];\n }\n /**\n * The scroll bar track node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get trackNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-track')[0];\n }\n /**\n * The scroll bar thumb node.\n *\n * #### Notes\n * Modifying this node directly can lead to undefined behavior.\n */\n get thumbNode() {\n return this.node.getElementsByClassName('lm-ScrollBar-thumb')[0];\n }\n /**\n * Handle the DOM events for the scroll bar.\n *\n * @param event - The DOM event sent to the scroll bar.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events on the scroll bar's DOM node.\n *\n * This should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'mousedown':\n this._evtMouseDown(event);\n break;\n case 'mousemove':\n this._evtMouseMove(event);\n break;\n case 'mouseup':\n this._evtMouseUp(event);\n break;\n case 'keydown':\n this._evtKeyDown(event);\n break;\n case 'contextmenu':\n event.preventDefault();\n event.stopPropagation();\n break;\n }\n }\n /**\n * A method invoked on a 'before-attach' message.\n */\n onBeforeAttach(msg) {\n this.node.addEventListener('mousedown', this);\n this.update();\n }\n /**\n * A method invoked on an 'after-detach' message.\n */\n onAfterDetach(msg) {\n this.node.removeEventListener('mousedown', this);\n this._releaseMouse();\n }\n /**\n * A method invoked on an 'update-request' message.\n */\n onUpdateRequest(msg) {\n // Convert the value and page into percentages.\n let value = (this._value * 100) / this._maximum;\n let page = (this._page * 100) / (this._page + this._maximum);\n // Clamp the value and page to the relevant range.\n value = Math.max(0, Math.min(value, 100));\n page = Math.max(0, Math.min(page, 100));\n // Fetch the thumb style.\n let thumbStyle = this.thumbNode.style;\n // Update the thumb style for the current orientation.\n if (this._orientation === 'horizontal') {\n thumbStyle.top = '';\n thumbStyle.height = '';\n thumbStyle.left = `${value}%`;\n thumbStyle.width = `${page}%`;\n thumbStyle.transform = `translate(${-value}%, 0%)`;\n }\n else {\n thumbStyle.left = '';\n thumbStyle.width = '';\n thumbStyle.top = `${value}%`;\n thumbStyle.height = `${page}%`;\n thumbStyle.transform = `translate(0%, ${-value}%)`;\n }\n }\n /**\n * Handle the `'keydown'` event for the scroll bar.\n */\n _evtKeyDown(event) {\n // Stop all input events during drag.\n event.preventDefault();\n event.stopPropagation();\n // Ignore anything except the `Escape` key.\n if (event.keyCode !== 27) {\n return;\n }\n // Fetch the previous scroll value.\n let value = this._pressData ? this._pressData.value : -1;\n // Release the mouse.\n this._releaseMouse();\n // Restore the old scroll value if possible.\n if (value !== -1) {\n this._moveThumb(value);\n }\n }\n /**\n * Handle the `'mousedown'` event for the scroll bar.\n */\n _evtMouseDown(event) {\n // Do nothing if it's not a left mouse press.\n if (event.button !== 0) {\n return;\n }\n // Send an activate request to the scroll bar. This can be\n // used by message hooks to activate something relevant.\n this.activate();\n // Do nothing if the mouse is already captured.\n if (this._pressData) {\n return;\n }\n // Find the pressed scroll bar part.\n let part = Private$2.findPart(this, event.target);\n // Do nothing if the part is not of interest.\n if (!part) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Override the mouse cursor.\n let override = Drag.overrideCursor('default');\n // Set up the press data.\n this._pressData = {\n part,\n override,\n delta: -1,\n value: -1,\n mouseX: event.clientX,\n mouseY: event.clientY\n };\n // Add the extra event listeners.\n document.addEventListener('mousemove', this, true);\n document.addEventListener('mouseup', this, true);\n document.addEventListener('keydown', this, true);\n document.addEventListener('contextmenu', this, true);\n // Handle a thumb press.\n if (part === 'thumb') {\n // Fetch the thumb node.\n let thumbNode = this.thumbNode;\n // Fetch the client rect for the thumb.\n let thumbRect = thumbNode.getBoundingClientRect();\n // Update the press data delta for the current orientation.\n if (this._orientation === 'horizontal') {\n this._pressData.delta = event.clientX - thumbRect.left;\n }\n else {\n this._pressData.delta = event.clientY - thumbRect.top;\n }\n // Add the active class to the thumb node.\n thumbNode.classList.add('lm-mod-active');\n // Store the current value in the press data.\n this._pressData.value = this._value;\n // Finished.\n return;\n }\n // Handle a track press.\n if (part === 'track') {\n // Fetch the client rect for the thumb.\n let thumbRect = this.thumbNode.getBoundingClientRect();\n // Determine the direction for the page request.\n let dir;\n if (this._orientation === 'horizontal') {\n dir = event.clientX < thumbRect.left ? 'decrement' : 'increment';\n }\n else {\n dir = event.clientY < thumbRect.top ? 'decrement' : 'increment';\n }\n // Start the repeat timer.\n this._repeatTimer = window.setTimeout(this._onRepeat, 350);\n // Emit the page requested signal.\n this._pageRequested.emit(dir);\n // Finished.\n return;\n }\n // Handle a decrement button press.\n if (part === 'decrement') {\n // Add the active class to the decrement node.\n this.decrementNode.classList.add('lm-mod-active');\n // Start the repeat timer.\n this._repeatTimer = window.setTimeout(this._onRepeat, 350);\n // Emit the step requested signal.\n this._stepRequested.emit('decrement');\n // Finished.\n return;\n }\n // Handle an increment button press.\n if (part === 'increment') {\n // Add the active class to the increment node.\n this.incrementNode.classList.add('lm-mod-active');\n // Start the repeat timer.\n this._repeatTimer = window.setTimeout(this._onRepeat, 350);\n // Emit the step requested signal.\n this._stepRequested.emit('increment');\n // Finished.\n return;\n }\n }\n /**\n * Handle the `'mousemove'` event for the scroll bar.\n */\n _evtMouseMove(event) {\n // Do nothing if no drag is in progress.\n if (!this._pressData) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Update the mouse position.\n this._pressData.mouseX = event.clientX;\n this._pressData.mouseY = event.clientY;\n // Bail if the thumb is not being dragged.\n if (this._pressData.part !== 'thumb') {\n return;\n }\n // Get the client rect for the thumb and track.\n let thumbRect = this.thumbNode.getBoundingClientRect();\n let trackRect = this.trackNode.getBoundingClientRect();\n // Fetch the scroll geometry based on the orientation.\n let trackPos;\n let trackSpan;\n if (this._orientation === 'horizontal') {\n trackPos = event.clientX - trackRect.left - this._pressData.delta;\n trackSpan = trackRect.width - thumbRect.width;\n }\n else {\n trackPos = event.clientY - trackRect.top - this._pressData.delta;\n trackSpan = trackRect.height - thumbRect.height;\n }\n // Compute the desired value from the scroll geometry.\n let value = trackSpan === 0 ? 0 : (trackPos * this._maximum) / trackSpan;\n // Move the thumb to the computed value.\n this._moveThumb(value);\n }\n /**\n * Handle the `'mouseup'` event for the scroll bar.\n */\n _evtMouseUp(event) {\n // Do nothing if it's not a left mouse release.\n if (event.button !== 0) {\n return;\n }\n // Stop the event propagation.\n event.preventDefault();\n event.stopPropagation();\n // Release the mouse.\n this._releaseMouse();\n }\n /**\n * Release the mouse and restore the node states.\n */\n _releaseMouse() {\n // Bail if there is no press data.\n if (!this._pressData) {\n return;\n }\n // Clear the repeat timer.\n clearTimeout(this._repeatTimer);\n this._repeatTimer = -1;\n // Clear the press data.\n this._pressData.override.dispose();\n this._pressData = null;\n // Remove the extra event listeners.\n document.removeEventListener('mousemove', this, true);\n document.removeEventListener('mouseup', this, true);\n document.removeEventListener('keydown', this, true);\n document.removeEventListener('contextmenu', this, true);\n // Remove the active classes from the nodes.\n this.thumbNode.classList.remove('lm-mod-active');\n this.decrementNode.classList.remove('lm-mod-active');\n this.incrementNode.classList.remove('lm-mod-active');\n }\n /**\n * Move the thumb to the specified position.\n */\n _moveThumb(value) {\n // Clamp the value to the allowed range.\n value = Math.max(0, Math.min(value, this._maximum));\n // Bail if the value does not change.\n if (this._value === value) {\n return;\n }\n // Update the internal value.\n this._value = value;\n // Schedule an update of the scroll bar.\n this.update();\n // Emit the thumb moved signal.\n this._thumbMoved.emit(value);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$2;\n(function (Private) {\n /**\n * Create the DOM node for a scroll bar.\n */\n function createNode() {\n let node = document.createElement('div');\n let decrement = document.createElement('div');\n let increment = document.createElement('div');\n let track = document.createElement('div');\n let thumb = document.createElement('div');\n decrement.className = 'lm-ScrollBar-button';\n increment.className = 'lm-ScrollBar-button';\n decrement.dataset['action'] = 'decrement';\n increment.dataset['action'] = 'increment';\n track.className = 'lm-ScrollBar-track';\n thumb.className = 'lm-ScrollBar-thumb';\n track.appendChild(thumb);\n node.appendChild(decrement);\n node.appendChild(track);\n node.appendChild(increment);\n return node;\n }\n Private.createNode = createNode;\n /**\n * Find the scroll bar part which contains the given target.\n */\n function findPart(scrollBar, target) {\n // Test the thumb.\n if (scrollBar.thumbNode.contains(target)) {\n return 'thumb';\n }\n // Test the track.\n if (scrollBar.trackNode.contains(target)) {\n return 'track';\n }\n // Test the decrement button.\n if (scrollBar.decrementNode.contains(target)) {\n return 'decrement';\n }\n // Test the increment button.\n if (scrollBar.incrementNode.contains(target)) {\n return 'increment';\n }\n // Indicate no match.\n return null;\n }\n Private.findPart = findPart;\n})(Private$2 || (Private$2 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A concrete layout implementation which holds a single widget.\n *\n * #### Notes\n * This class is useful for creating simple container widgets which\n * hold a single child. The child should be positioned with CSS.\n */\nclass SingletonLayout extends Layout {\n constructor() {\n super(...arguments);\n this._widget = null;\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n if (this._widget) {\n let widget = this._widget;\n this._widget = null;\n widget.dispose();\n }\n super.dispose();\n }\n /**\n * Get the child widget for the layout.\n */\n get widget() {\n return this._widget;\n }\n /**\n * Set the child widget for the layout.\n *\n * #### Notes\n * Setting the child widget will cause the old child widget to be\n * automatically disposed. If that is not desired, set the parent\n * of the old child to `null` before assigning a new child.\n */\n set widget(widget) {\n // Remove the widget from its current parent. This is a no-op\n // if the widget's parent is already the layout parent widget.\n if (widget) {\n widget.parent = this.parent;\n }\n // Bail early if the widget does not change.\n if (this._widget === widget) {\n return;\n }\n // Dispose of the old child widget.\n if (this._widget) {\n this._widget.dispose();\n }\n // Update the internal widget.\n this._widget = widget;\n // Attach the new child widget if needed.\n if (this.parent && widget) {\n this.attachWidget(widget);\n }\n }\n /**\n * Create an iterator over the widgets in the layout.\n *\n * @returns A new iterator over the widgets in the layout.\n */\n *[Symbol.iterator]() {\n if (this._widget) {\n yield this._widget;\n }\n }\n /**\n * Remove a widget from the layout.\n *\n * @param widget - The widget to remove from the layout.\n *\n * #### Notes\n * A widget is automatically removed from the layout when its `parent`\n * is set to `null`. This method should only be invoked directly when\n * removing a widget from a layout which has yet to be installed on a\n * parent widget.\n *\n * This method does *not* modify the widget's `parent`.\n */\n removeWidget(widget) {\n // Bail early if the widget does not exist in the layout.\n if (this._widget !== widget) {\n return;\n }\n // Clear the internal widget.\n this._widget = null;\n // If the layout is parented, detach the widget from the DOM.\n if (this.parent) {\n this.detachWidget(widget);\n }\n }\n /**\n * Perform layout initialization which requires the parent widget.\n */\n init() {\n super.init();\n for (const widget of this) {\n this.attachWidget(widget);\n }\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This method is called automatically by the single layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation adds the widgets's node to the parent's\n * node at the proper location, and sends the appropriate attach\n * messages to the widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is added to the parent's node.\n */\n attachWidget(widget) {\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This method is called automatically by the single layout at the\n * appropriate time. It should not be called directly by user code.\n *\n * The default implementation removes the widget's node from the\n * parent's node, and sends the appropriate detach messages to the\n * widget if the parent is attached to the DOM.\n *\n * Subclasses may reimplement this method to control how the widget's\n * node is removed from the parent's node.\n */\n detachWidget(widget) {\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A layout where visible widgets are stacked atop one another.\n *\n * #### Notes\n * The Z-order of the visible widgets follows their layout order.\n */\nclass StackedLayout extends PanelLayout {\n constructor(options = {}) {\n super(options);\n this._dirty = false;\n this._items = [];\n this._box = null;\n this._hiddenMode =\n options.hiddenMode !== undefined\n ? options.hiddenMode\n : Widget.HiddenMode.Display;\n }\n /**\n * The method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n get hiddenMode() {\n return this._hiddenMode;\n }\n /**\n * Set the method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n set hiddenMode(v) {\n if (this._hiddenMode === v) {\n return;\n }\n this._hiddenMode = v;\n if (this.widgets.length > 1) {\n this.widgets.forEach(w => {\n w.hiddenMode = this._hiddenMode;\n });\n }\n }\n /**\n * Dispose of the resources held by the layout.\n */\n dispose() {\n // Dispose of the layout items.\n for (const item of this._items) {\n item.dispose();\n }\n // Clear the layout state.\n this._box = null;\n this._items.length = 0;\n // Dispose of the rest of the layout.\n super.dispose();\n }\n /**\n * Attach a widget to the parent's DOM node.\n *\n * @param index - The current index of the widget in the layout.\n *\n * @param widget - The widget to attach to the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n attachWidget(index, widget) {\n // Using transform create an additional layer in the pixel pipeline\n // to limit the number of layer, it is set only if there is more than one widget.\n if (this._hiddenMode === Widget.HiddenMode.Scale &&\n this._items.length > 0) {\n if (this._items.length === 1) {\n this.widgets[0].hiddenMode = Widget.HiddenMode.Scale;\n }\n widget.hiddenMode = Widget.HiddenMode.Scale;\n }\n else {\n widget.hiddenMode = Widget.HiddenMode.Display;\n }\n // Create and add a new layout item for the widget.\n ArrayExt.insert(this._items, index, new LayoutItem(widget));\n // Send a `'before-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);\n }\n // Add the widget's node to the parent.\n this.parent.node.appendChild(widget.node);\n // Send an `'after-attach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);\n }\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * Move a widget in the parent's DOM node.\n *\n * @param fromIndex - The previous index of the widget in the layout.\n *\n * @param toIndex - The current index of the widget in the layout.\n *\n * @param widget - The widget to move in the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n moveWidget(fromIndex, toIndex, widget) {\n // Move the layout item for the widget.\n ArrayExt.move(this._items, fromIndex, toIndex);\n // Post an update request for the parent widget.\n this.parent.update();\n }\n /**\n * Detach a widget from the parent's DOM node.\n *\n * @param index - The previous index of the widget in the layout.\n *\n * @param widget - The widget to detach from the parent.\n *\n * #### Notes\n * This is a reimplementation of the superclass method.\n */\n detachWidget(index, widget) {\n // Remove the layout item for the widget.\n let item = ArrayExt.removeAt(this._items, index);\n // Send a `'before-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);\n }\n // Remove the widget's node from the parent.\n this.parent.node.removeChild(widget.node);\n // Send an `'after-detach'` message if the parent is attached.\n if (this.parent.isAttached) {\n MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);\n }\n // Reset the z-index for the widget.\n item.widget.node.style.zIndex = '';\n // Reset the hidden mode for the widget.\n if (this._hiddenMode === Widget.HiddenMode.Scale) {\n widget.hiddenMode = Widget.HiddenMode.Display;\n // Reset the hidden mode for the first widget if necessary.\n if (this._items.length === 1) {\n this._items[0].widget.hiddenMode = Widget.HiddenMode.Display;\n }\n }\n // Dispose of the layout item.\n item.dispose();\n // Post a fit request for the parent widget.\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'before-show'` message.\n */\n onBeforeShow(msg) {\n super.onBeforeShow(msg);\n this.parent.update();\n }\n /**\n * A message handler invoked on a `'before-attach'` message.\n */\n onBeforeAttach(msg) {\n super.onBeforeAttach(msg);\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-shown'` message.\n */\n onChildShown(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'child-hidden'` message.\n */\n onChildHidden(msg) {\n this.parent.fit();\n }\n /**\n * A message handler invoked on a `'resize'` message.\n */\n onResize(msg) {\n if (this.parent.isVisible) {\n this._update(msg.width, msg.height);\n }\n }\n /**\n * A message handler invoked on an `'update-request'` message.\n */\n onUpdateRequest(msg) {\n if (this.parent.isVisible) {\n this._update(-1, -1);\n }\n }\n /**\n * A message handler invoked on a `'fit-request'` message.\n */\n onFitRequest(msg) {\n if (this.parent.isAttached) {\n this._fit();\n }\n }\n /**\n * Fit the layout to the total size required by the widgets.\n */\n _fit() {\n // Set up the computed minimum size.\n let minW = 0;\n let minH = 0;\n // Update the computed minimum size.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Update the size limits for the item.\n item.fit();\n // Update the computed minimum size.\n minW = Math.max(minW, item.minWidth);\n minH = Math.max(minH, item.minHeight);\n }\n // Update the box sizing and add it to the computed min size.\n let box = (this._box = ElementExt.boxSizing(this.parent.node));\n minW += box.horizontalSum;\n minH += box.verticalSum;\n // Update the parent's min size constraints.\n let style = this.parent.node.style;\n style.minWidth = `${minW}px`;\n style.minHeight = `${minH}px`;\n // Set the dirty flag to ensure only a single update occurs.\n this._dirty = true;\n // Notify the ancestor that it should fit immediately. This may\n // cause a resize of the parent, fulfilling the required update.\n if (this.parent.parent) {\n MessageLoop.sendMessage(this.parent.parent, Widget.Msg.FitRequest);\n }\n // If the dirty flag is still set, the parent was not resized.\n // Trigger the required update on the parent widget immediately.\n if (this._dirty) {\n MessageLoop.sendMessage(this.parent, Widget.Msg.UpdateRequest);\n }\n }\n /**\n * Update the layout position and size of the widgets.\n *\n * The parent offset dimensions should be `-1` if unknown.\n */\n _update(offsetWidth, offsetHeight) {\n // Clear the dirty flag to indicate the update occurred.\n this._dirty = false;\n // Compute the visible item count.\n let nVisible = 0;\n for (let i = 0, n = this._items.length; i < n; ++i) {\n nVisible += +!this._items[i].isHidden;\n }\n // Bail early if there are no visible items to layout.\n if (nVisible === 0) {\n return;\n }\n // Measure the parent if the offset dimensions are unknown.\n if (offsetWidth < 0) {\n offsetWidth = this.parent.node.offsetWidth;\n }\n if (offsetHeight < 0) {\n offsetHeight = this.parent.node.offsetHeight;\n }\n // Ensure the parent box sizing data is computed.\n if (!this._box) {\n this._box = ElementExt.boxSizing(this.parent.node);\n }\n // Compute the actual layout bounds adjusted for border and padding.\n let top = this._box.paddingTop;\n let left = this._box.paddingLeft;\n let width = offsetWidth - this._box.horizontalSum;\n let height = offsetHeight - this._box.verticalSum;\n // Update the widget stacking order and layout geometry.\n for (let i = 0, n = this._items.length; i < n; ++i) {\n // Fetch the item.\n let item = this._items[i];\n // Ignore hidden items.\n if (item.isHidden) {\n continue;\n }\n // Set the z-index for the widget.\n item.widget.node.style.zIndex = `${i}`;\n // Update the item geometry.\n item.update(left, top, width, height);\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A panel where visible widgets are stacked atop one another.\n *\n * #### Notes\n * This class provides a convenience wrapper around a {@link StackedLayout}.\n */\nclass StackedPanel extends Panel {\n /**\n * Construct a new stacked panel.\n *\n * @param options - The options for initializing the panel.\n */\n constructor(options = {}) {\n super({ layout: Private$1.createLayout(options) });\n this._widgetRemoved = new Signal(this);\n this.addClass('lm-StackedPanel');\n }\n /**\n * The method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n get hiddenMode() {\n return this.layout.hiddenMode;\n }\n /**\n * Set the method for hiding widgets.\n *\n * #### Notes\n * If there is only one child widget, `Display` hiding mode will be used\n * regardless of this setting.\n */\n set hiddenMode(v) {\n this.layout.hiddenMode = v;\n }\n /**\n * A signal emitted when a widget is removed from a stacked panel.\n */\n get widgetRemoved() {\n return this._widgetRemoved;\n }\n /**\n * A message handler invoked on a `'child-added'` message.\n */\n onChildAdded(msg) {\n msg.child.addClass('lm-StackedPanel-child');\n }\n /**\n * A message handler invoked on a `'child-removed'` message.\n */\n onChildRemoved(msg) {\n msg.child.removeClass('lm-StackedPanel-child');\n this._widgetRemoved.emit(msg.child);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private$1;\n(function (Private) {\n /**\n * Create a stacked layout for the given panel options.\n */\n function createLayout(options) {\n return options.layout || new StackedLayout();\n }\n Private.createLayout = createLayout;\n})(Private$1 || (Private$1 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A widget which combines a `TabBar` and a `StackedPanel`.\n *\n * #### Notes\n * This is a simple panel which handles the common case of a tab bar\n * placed next to a content area. The selected tab controls the widget\n * which is shown in the content area.\n *\n * For use cases which require more control than is provided by this\n * panel, the `TabBar` widget may be used independently.\n */\nclass TabPanel extends Widget {\n /**\n * Construct a new tab panel.\n *\n * @param options - The options for initializing the tab panel.\n */\n constructor(options = {}) {\n super();\n this._currentChanged = new Signal(this);\n this._addRequested = new Signal(this);\n this.addClass('lm-TabPanel');\n // Create the tab bar and stacked panel.\n this.tabBar = new TabBar(options);\n this.tabBar.addClass('lm-TabPanel-tabBar');\n this.stackedPanel = new StackedPanel();\n this.stackedPanel.addClass('lm-TabPanel-stackedPanel');\n // Connect the tab bar signal handlers.\n this.tabBar.tabMoved.connect(this._onTabMoved, this);\n this.tabBar.currentChanged.connect(this._onCurrentChanged, this);\n this.tabBar.tabCloseRequested.connect(this._onTabCloseRequested, this);\n this.tabBar.tabActivateRequested.connect(this._onTabActivateRequested, this);\n this.tabBar.addRequested.connect(this._onTabAddRequested, this);\n // Connect the stacked panel signal handlers.\n this.stackedPanel.widgetRemoved.connect(this._onWidgetRemoved, this);\n // Get the data related to the placement.\n this._tabPlacement = options.tabPlacement || 'top';\n let direction = Private.directionFromPlacement(this._tabPlacement);\n let orientation = Private.orientationFromPlacement(this._tabPlacement);\n // Configure the tab bar for the placement.\n this.tabBar.orientation = orientation;\n this.tabBar.dataset['placement'] = this._tabPlacement;\n // Create the box layout.\n let layout = new BoxLayout({ direction, spacing: 0 });\n // Set the stretch factors for the child widgets.\n BoxLayout.setStretch(this.tabBar, 0);\n BoxLayout.setStretch(this.stackedPanel, 1);\n // Add the child widgets to the layout.\n layout.addWidget(this.tabBar);\n layout.addWidget(this.stackedPanel);\n // Install the layout on the tab panel.\n this.layout = layout;\n }\n /**\n * A signal emitted when the current tab is changed.\n *\n * #### Notes\n * This signal is emitted when the currently selected tab is changed\n * either through user or programmatic interaction.\n *\n * Notably, this signal is not emitted when the index of the current\n * tab changes due to tabs being inserted, removed, or moved. It is\n * only emitted when the actual current tab node is changed.\n */\n get currentChanged() {\n return this._currentChanged;\n }\n /**\n * Get the index of the currently selected tab.\n *\n * #### Notes\n * This will be `-1` if no tab is selected.\n */\n get currentIndex() {\n return this.tabBar.currentIndex;\n }\n /**\n * Set the index of the currently selected tab.\n *\n * #### Notes\n * If the index is out of range, it will be set to `-1`.\n */\n set currentIndex(value) {\n this.tabBar.currentIndex = value;\n }\n /**\n * Get the currently selected widget.\n *\n * #### Notes\n * This will be `null` if there is no selected tab.\n */\n get currentWidget() {\n let title = this.tabBar.currentTitle;\n return title ? title.owner : null;\n }\n /**\n * Set the currently selected widget.\n *\n * #### Notes\n * If the widget is not in the panel, it will be set to `null`.\n */\n set currentWidget(value) {\n this.tabBar.currentTitle = value ? value.title : null;\n }\n /**\n * Get the whether the tabs are movable by the user.\n *\n * #### Notes\n * Tabs can always be moved programmatically.\n */\n get tabsMovable() {\n return this.tabBar.tabsMovable;\n }\n /**\n * Set the whether the tabs are movable by the user.\n *\n * #### Notes\n * Tabs can always be moved programmatically.\n */\n set tabsMovable(value) {\n this.tabBar.tabsMovable = value;\n }\n /**\n * Get the whether the add button is enabled.\n *\n */\n get addButtonEnabled() {\n return this.tabBar.addButtonEnabled;\n }\n /**\n * Set the whether the add button is enabled.\n *\n */\n set addButtonEnabled(value) {\n this.tabBar.addButtonEnabled = value;\n }\n /**\n * Get the tab placement for the tab panel.\n *\n * #### Notes\n * This controls the position of the tab bar relative to the content.\n */\n get tabPlacement() {\n return this._tabPlacement;\n }\n /**\n * Set the tab placement for the tab panel.\n *\n * #### Notes\n * This controls the position of the tab bar relative to the content.\n */\n set tabPlacement(value) {\n // Bail if the placement does not change.\n if (this._tabPlacement === value) {\n return;\n }\n // Update the internal value.\n this._tabPlacement = value;\n // Get the values related to the placement.\n let direction = Private.directionFromPlacement(value);\n let orientation = Private.orientationFromPlacement(value);\n // Configure the tab bar for the placement.\n this.tabBar.orientation = orientation;\n this.tabBar.dataset['placement'] = value;\n // Update the layout direction.\n this.layout.direction = direction;\n }\n /**\n * A signal emitted when the add button on a tab bar is clicked.\n *\n */\n get addRequested() {\n return this._addRequested;\n }\n /**\n * A read-only array of the widgets in the panel.\n */\n get widgets() {\n return this.stackedPanel.widgets;\n }\n /**\n * Add a widget to the end of the tab panel.\n *\n * @param widget - The widget to add to the tab panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n *\n * The widget's `title` is used to populate the tab.\n */\n addWidget(widget) {\n this.insertWidget(this.widgets.length, widget);\n }\n /**\n * Insert a widget into the tab panel at a specified index.\n *\n * @param index - The index at which to insert the widget.\n *\n * @param widget - The widget to insert into to the tab panel.\n *\n * #### Notes\n * If the widget is already contained in the panel, it will be moved.\n *\n * The widget's `title` is used to populate the tab.\n */\n insertWidget(index, widget) {\n if (widget !== this.currentWidget) {\n widget.hide();\n }\n this.stackedPanel.insertWidget(index, widget);\n this.tabBar.insertTab(index, widget.title);\n widget.node.setAttribute('role', 'tabpanel');\n let renderer = this.tabBar.renderer;\n if (renderer instanceof TabBar.Renderer) {\n let tabId = renderer.createTabKey({\n title: widget.title,\n current: false,\n zIndex: 0\n });\n widget.node.setAttribute('aria-labelledby', tabId);\n }\n }\n /**\n * Handle the `currentChanged` signal from the tab bar.\n */\n _onCurrentChanged(sender, args) {\n // Extract the previous and current title from the args.\n let { previousIndex, previousTitle, currentIndex, currentTitle } = args;\n // Extract the widgets from the titles.\n let previousWidget = previousTitle ? previousTitle.owner : null;\n let currentWidget = currentTitle ? currentTitle.owner : null;\n // Hide the previous widget.\n if (previousWidget) {\n previousWidget.hide();\n }\n // Show the current widget.\n if (currentWidget) {\n currentWidget.show();\n }\n // Emit the `currentChanged` signal for the tab panel.\n this._currentChanged.emit({\n previousIndex,\n previousWidget,\n currentIndex,\n currentWidget\n });\n // Flush the message loop on IE and Edge to prevent flicker.\n if (Platform.IS_EDGE || Platform.IS_IE) {\n MessageLoop.flush();\n }\n }\n /**\n * Handle the `tabAddRequested` signal from the tab bar.\n */\n _onTabAddRequested(sender, args) {\n this._addRequested.emit(sender);\n }\n /**\n * Handle the `tabActivateRequested` signal from the tab bar.\n */\n _onTabActivateRequested(sender, args) {\n args.title.owner.activate();\n }\n /**\n * Handle the `tabCloseRequested` signal from the tab bar.\n */\n _onTabCloseRequested(sender, args) {\n args.title.owner.close();\n }\n /**\n * Handle the `tabMoved` signal from the tab bar.\n */\n _onTabMoved(sender, args) {\n this.stackedPanel.insertWidget(args.toIndex, args.title.owner);\n }\n /**\n * Handle the `widgetRemoved` signal from the stacked panel.\n */\n _onWidgetRemoved(sender, widget) {\n widget.node.removeAttribute('role');\n widget.node.removeAttribute('aria-labelledby');\n this.tabBar.removeTab(widget.title);\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Convert a tab placement to tab bar orientation.\n */\n function orientationFromPlacement(plc) {\n return placementToOrientationMap[plc];\n }\n Private.orientationFromPlacement = orientationFromPlacement;\n /**\n * Convert a tab placement to a box layout direction.\n */\n function directionFromPlacement(plc) {\n return placementToDirectionMap[plc];\n }\n Private.directionFromPlacement = directionFromPlacement;\n /**\n * A mapping of tab placement to tab bar orientation.\n */\n const placementToOrientationMap = {\n top: 'horizontal',\n left: 'vertical',\n right: 'vertical',\n bottom: 'horizontal'\n };\n /**\n * A mapping of tab placement to box layout direction.\n */\n const placementToDirectionMap = {\n top: 'top-to-bottom',\n left: 'left-to-right',\n right: 'right-to-left',\n bottom: 'bottom-to-top'\n };\n})(Private || (Private = {}));\n\nexport { AccordionLayout, AccordionPanel, BoxEngine, BoxLayout, BoxPanel, BoxSizer, CommandPalette, ContextMenu, DockLayout, DockPanel, FocusTracker, GridLayout, Layout, LayoutItem, Menu, MenuBar, Panel, PanelLayout, ScrollBar, SingletonLayout, SplitLayout, SplitPanel, StackedLayout, StackedPanel, TabBar, TabPanel, Title, Widget };\n//# sourceMappingURL=index.es6.js.map\n","import { CommandRegistry } from '@lumino/commands';\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport { ContextMenu, Widget } from '@lumino/widgets';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n/**\n * The namespace for the module implementation details.\n */\nvar Private$1;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private$1 || (Private$1 = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module application\n */\n/**\n * A class for creating pluggable applications.\n *\n * @typeparam T - The type of the application shell.\n *\n * #### Notes\n * The `Application` class is useful when creating large, complex\n * UI applications with the ability to be safely extended by third\n * party code via plugins.\n */\nclass Application {\n /**\n * Construct a new application.\n *\n * @param options - The options for creating the application.\n */\n constructor(options) {\n this._delegate = new PromiseDelegate();\n this._plugins = new Map();\n this._services = new Map();\n this._started = false;\n this._bubblingKeydown = false;\n // Initialize the application state.\n this.commands = new CommandRegistry();\n this.contextMenu = new ContextMenu({\n commands: this.commands,\n renderer: options.contextMenuRenderer\n });\n this.shell = options.shell;\n }\n /**\n * A promise which resolves after the application has started.\n *\n * #### Notes\n * This promise will resolve after the `start()` method is called,\n * when all the bootstrapping and shell mounting work is complete.\n */\n get started() {\n return this._delegate.promise;\n }\n /**\n * Get a plugin description.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns The plugin description.\n */\n getPluginDescription(id) {\n var _a, _b;\n return (_b = (_a = this._plugins.get(id)) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : '';\n }\n /**\n * Test whether a plugin is registered with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is registered, `false` otherwise.\n */\n hasPlugin(id) {\n return this._plugins.has(id);\n }\n /**\n * Test whether a plugin is activated with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is activated, `false` otherwise.\n */\n isPluginActivated(id) {\n var _a, _b;\n return (_b = (_a = this._plugins.get(id)) === null || _a === void 0 ? void 0 : _a.activated) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * List the IDs of the plugins registered with the application.\n *\n * @returns A new array of the registered plugin IDs.\n */\n listPlugins() {\n return Array.from(this._plugins.keys());\n }\n /**\n * Register a plugin with the application.\n *\n * @param plugin - The plugin to register.\n *\n * #### Notes\n * An error will be thrown if a plugin with the same ID is already\n * registered, or if the plugin has a circular dependency.\n *\n * If the plugin provides a service which has already been provided\n * by another plugin, the new service will override the old service.\n */\n registerPlugin(plugin) {\n // Throw an error if the plugin ID is already registered.\n if (this._plugins.has(plugin.id)) {\n throw new TypeError(`Plugin '${plugin.id}' is already registered.`);\n }\n // Create the normalized plugin data.\n const data = Private.createPluginData(plugin);\n // Ensure the plugin does not cause a cyclic dependency.\n Private.ensureNoCycle(data, this._plugins, this._services);\n // Add the service token to the service map.\n if (data.provides) {\n this._services.set(data.provides, data.id);\n }\n // Add the plugin to the plugin map.\n this._plugins.set(data.id, data);\n }\n /**\n * Register multiple plugins with the application.\n *\n * @param plugins - The plugins to register.\n *\n * #### Notes\n * This calls `registerPlugin()` for each of the given plugins.\n */\n registerPlugins(plugins) {\n for (const plugin of plugins) {\n this.registerPlugin(plugin);\n }\n }\n /**\n * Deregister a plugin with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param force - Whether to deregister the plugin even if it is active.\n */\n deregisterPlugin(id, force) {\n const plugin = this._plugins.get(id);\n if (!plugin) {\n return;\n }\n if (plugin.activated && !force) {\n throw new Error(`Plugin '${id}' is still active.`);\n }\n this._plugins.delete(id);\n }\n /**\n * Activate the plugin with the given ID.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A promise which resolves when the plugin is activated\n * or rejects with an error if it cannot be activated.\n */\n async activatePlugin(id) {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n // Resolve immediately if the plugin is already activated.\n if (plugin.activated) {\n return;\n }\n // Return the pending resolver promise if it exists.\n if (plugin.promise) {\n return plugin.promise;\n }\n // Resolve the required services for the plugin.\n const required = plugin.requires.map(t => this.resolveRequiredService(t));\n // Resolve the optional services for the plugin.\n const optional = plugin.optional.map(t => this.resolveOptionalService(t));\n // Setup the resolver promise for the plugin.\n plugin.promise = Promise.all([...required, ...optional])\n .then(services => plugin.activate.apply(undefined, [this, ...services]))\n .then(service => {\n plugin.service = service;\n plugin.activated = true;\n plugin.promise = null;\n })\n .catch(error => {\n plugin.promise = null;\n throw error;\n });\n // Return the pending resolver promise.\n return plugin.promise;\n }\n /**\n * Deactivate the plugin and its downstream dependents if and only if the\n * plugin and its dependents all support `deactivate`.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A list of IDs of downstream plugins deactivated with this one.\n */\n async deactivatePlugin(id) {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n // Bail early if the plugin is not activated.\n if (!plugin.activated) {\n return [];\n }\n // Check that this plugin can deactivate.\n if (!plugin.deactivate) {\n throw new TypeError(`Plugin '${id}'#deactivate() method missing`);\n }\n // Find the optimal deactivation order for plugins downstream of this one.\n const manifest = Private.findDependents(id, this._plugins, this._services);\n const downstream = manifest.map(id => this._plugins.get(id));\n // Check that all downstream plugins can deactivate.\n for (const plugin of downstream) {\n if (!plugin.deactivate) {\n throw new TypeError(`Plugin ${plugin.id}#deactivate() method missing (depends on ${id})`);\n }\n }\n // Deactivate all downstream plugins.\n for (const plugin of downstream) {\n const services = [...plugin.requires, ...plugin.optional].map(service => {\n const id = this._services.get(service);\n return id ? this._plugins.get(id).service : null;\n });\n // Await deactivation so the next plugins only receive active services.\n await plugin.deactivate(this, ...services);\n plugin.service = null;\n plugin.activated = false;\n }\n // Remove plugin ID and return manifest of deactivated plugins.\n manifest.pop();\n return manifest;\n }\n /**\n * Resolve a required service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or rejects with an error if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the required services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveRequiredService(token) {\n // Reject the promise if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n throw new TypeError(`No provider for: ${token.name}.`);\n }\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id);\n if (!plugin.activated) {\n await this.activatePlugin(id);\n }\n return plugin.service;\n }\n /**\n * Resolve an optional service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or `null` if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the optional services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveOptionalService(token) {\n // Resolve with `null` if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n return null;\n }\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id);\n if (!plugin.activated) {\n try {\n await this.activatePlugin(id);\n }\n catch (reason) {\n console.error(reason);\n return null;\n }\n }\n return plugin.service;\n }\n /**\n * Start the application.\n *\n * @param options - The options for starting the application.\n *\n * @returns A promise which resolves when all bootstrapping work\n * is complete and the shell is mounted to the DOM.\n *\n * #### Notes\n * This should be called once by the application creator after all\n * initial plugins have been registered.\n *\n * If a plugin fails to the load, the error will be logged and the\n * other valid plugins will continue to be loaded.\n *\n * Bootstrapping the application consists of the following steps:\n * 1. Activate the startup plugins\n * 2. Wait for those plugins to activate\n * 3. Attach the shell widget to the DOM\n * 4. Add the application event listeners\n */\n start(options = {}) {\n // Return immediately if the application is already started.\n if (this._started) {\n return this._delegate.promise;\n }\n // Mark the application as started;\n this._started = true;\n this._bubblingKeydown = options.bubblingKeydown || false;\n // Parse the host ID for attaching the shell.\n const hostID = options.hostID || '';\n // Collect the ids of the startup plugins.\n const startups = Private.collectStartupPlugins(this._plugins, options);\n // Generate the activation promises.\n const promises = startups.map(id => {\n return this.activatePlugin(id).catch(error => {\n console.error(`Plugin '${id}' failed to activate.`);\n console.error(error);\n });\n });\n // Wait for the plugins to activate, then finalize startup.\n Promise.all(promises).then(() => {\n this.attachShell(hostID);\n this.addEventListeners();\n this._delegate.resolve();\n });\n // Return the pending delegate promise.\n return this._delegate.promise;\n }\n /**\n * The list of all the deferred plugins.\n */\n get deferredPlugins() {\n return Array.from(this._plugins)\n .filter(([id, plugin]) => plugin.autoStart === 'defer')\n .map(([id, plugin]) => id);\n }\n /**\n * Activate all the deferred plugins.\n *\n * @returns A promise which will resolve when each plugin is activated\n * or rejects with an error if one cannot be activated.\n */\n async activateDeferredPlugins() {\n const promises = this.deferredPlugins\n .filter(pluginId => this._plugins.get(pluginId).autoStart)\n .map(pluginId => {\n return this.activatePlugin(pluginId);\n });\n await Promise.all(promises);\n }\n /**\n * Handle the DOM events for the application.\n *\n * @param event - The DOM event sent to the application.\n *\n * #### Notes\n * This method implements the DOM `EventListener` interface and is\n * called in response to events registered for the application. It\n * should not be called directly by user code.\n */\n handleEvent(event) {\n switch (event.type) {\n case 'resize':\n this.evtResize(event);\n break;\n case 'keydown':\n this.evtKeydown(event);\n break;\n case 'contextmenu':\n this.evtContextMenu(event);\n break;\n }\n }\n /**\n * Attach the application shell to the DOM.\n *\n * @param id - The ID of the host node for the shell, or `''`.\n *\n * #### Notes\n * If the ID is not provided, the document body will be the host.\n *\n * A subclass may reimplement this method as needed.\n */\n attachShell(id) {\n Widget.attach(this.shell, (id && document.getElementById(id)) || document.body);\n }\n /**\n * Add the application event listeners.\n *\n * #### Notes\n * The default implementation of this method adds listeners for\n * `'keydown'` and `'resize'` events.\n *\n * A subclass may reimplement this method as needed.\n */\n addEventListeners() {\n document.addEventListener('contextmenu', this);\n document.addEventListener('keydown', this, !this._bubblingKeydown);\n window.addEventListener('resize', this);\n }\n /**\n * A method invoked on a document `'keydown'` event.\n *\n * #### Notes\n * The default implementation of this method invokes the key down\n * processing method of the application command registry.\n *\n * A subclass may reimplement this method as needed.\n */\n evtKeydown(event) {\n this.commands.processKeydownEvent(event);\n }\n /**\n * A method invoked on a document `'contextmenu'` event.\n *\n * #### Notes\n * The default implementation of this method opens the application\n * `contextMenu` at the current mouse position.\n *\n * If the application context menu has no matching content *or* if\n * the shift key is pressed, the default browser context menu will\n * be opened instead.\n *\n * A subclass may reimplement this method as needed.\n */\n evtContextMenu(event) {\n if (event.shiftKey) {\n return;\n }\n if (this.contextMenu.open(event)) {\n event.preventDefault();\n event.stopPropagation();\n }\n }\n /**\n * A method invoked on a window `'resize'` event.\n *\n * #### Notes\n * The default implementation of this method updates the shell.\n *\n * A subclass may reimplement this method as needed.\n */\n evtResize(event) {\n this.shell.update();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Create a normalized plugin data object for the given plugin.\n */\n function createPluginData(plugin) {\n var _a, _b, _c, _d;\n return {\n id: plugin.id,\n description: (_a = plugin.description) !== null && _a !== void 0 ? _a : '',\n service: null,\n promise: null,\n activated: false,\n activate: plugin.activate,\n deactivate: (_b = plugin.deactivate) !== null && _b !== void 0 ? _b : null,\n provides: (_c = plugin.provides) !== null && _c !== void 0 ? _c : null,\n autoStart: (_d = plugin.autoStart) !== null && _d !== void 0 ? _d : false,\n requires: plugin.requires ? plugin.requires.slice() : [],\n optional: plugin.optional ? plugin.optional.slice() : []\n };\n }\n Private.createPluginData = createPluginData;\n /**\n * Ensure no cycle is present in the plugin resolution graph.\n *\n * If a cycle is detected, an error will be thrown.\n */\n function ensureNoCycle(plugin, plugins, services) {\n const dependencies = [...plugin.requires, ...plugin.optional];\n const visit = (token) => {\n if (token === plugin.provides) {\n return true;\n }\n const id = services.get(token);\n if (!id) {\n return false;\n }\n const visited = plugins.get(id);\n const dependencies = [...visited.requires, ...visited.optional];\n if (dependencies.length === 0) {\n return false;\n }\n trace.push(id);\n if (dependencies.some(visit)) {\n return true;\n }\n trace.pop();\n return false;\n };\n // Bail early if there cannot be a cycle.\n if (!plugin.provides || dependencies.length === 0) {\n return;\n }\n // Setup a stack to trace service resolution.\n const trace = [plugin.id];\n // Throw an exception if a cycle is present.\n if (dependencies.some(visit)) {\n throw new ReferenceError(`Cycle detected: ${trace.join(' -> ')}.`);\n }\n }\n Private.ensureNoCycle = ensureNoCycle;\n /**\n * Find dependents in deactivation order.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param plugins - The map containing all plugins.\n *\n * @param services - The map containing all services.\n *\n * @returns A list of dependent plugin IDs in order of deactivation\n *\n * #### Notes\n * The final item of the returned list is always the plugin of interest.\n */\n function findDependents(id, plugins, services) {\n const edges = new Array();\n const add = (id) => {\n const plugin = plugins.get(id);\n // FIXME In the case of missing optional dependencies, we may consider\n // deactivating and reactivating the plugin without the missing service.\n const dependencies = [...plugin.requires, ...plugin.optional];\n edges.push(...dependencies.reduce((acc, dep) => {\n const service = services.get(dep);\n if (service) {\n // An edge is oriented from dependent to provider.\n acc.push([id, service]);\n }\n return acc;\n }, []));\n };\n for (const id of plugins.keys()) {\n add(id);\n }\n // Filter edges\n // - Get all packages that dependent on the package to be deactivated\n const newEdges = edges.filter(edge => edge[1] === id);\n let oldSize = 0;\n while (newEdges.length > oldSize) {\n const previousSize = newEdges.length;\n // Get all packages that dependent on packages that will be deactivated\n const packagesOfInterest = new Set(newEdges.map(edge => edge[0]));\n for (const poi of packagesOfInterest) {\n edges\n .filter(edge => edge[1] === poi)\n .forEach(edge => {\n // We check it is not already included to deal with circular dependencies\n if (!newEdges.includes(edge)) {\n newEdges.push(edge);\n }\n });\n }\n oldSize = previousSize;\n }\n const sorted = topologicSort(newEdges);\n const index = sorted.findIndex(candidate => candidate === id);\n if (index === -1) {\n return [id];\n }\n return sorted.slice(0, index + 1);\n }\n Private.findDependents = findDependents;\n /**\n * Collect the IDs of the plugins to activate on startup.\n */\n function collectStartupPlugins(plugins, options) {\n // Create a set to hold the plugin IDs.\n const collection = new Set();\n // Collect the auto-start (non deferred) plugins.\n for (const id of plugins.keys()) {\n if (plugins.get(id).autoStart === true) {\n collection.add(id);\n }\n }\n // Add the startup plugins.\n if (options.startPlugins) {\n for (const id of options.startPlugins) {\n collection.add(id);\n }\n }\n // Remove the ignored plugins.\n if (options.ignorePlugins) {\n for (const id of options.ignorePlugins) {\n collection.delete(id);\n }\n }\n // Return the collected startup plugins.\n return Array.from(collection);\n }\n Private.collectStartupPlugins = collectStartupPlugins;\n})(Private || (Private = {}));\n\nexport { Application };\n//# sourceMappingURL=index.es6.js.map\n","/**\n * A simple router.\n */\nexport class Router {\n constructor() {\n this._routes = [];\n }\n /**\n * Add a new GET route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n get(pattern, callback) {\n this._add('GET', pattern, callback);\n }\n /**\n * Add a new PUT route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n put(pattern, callback) {\n this._add('PUT', pattern, callback);\n }\n /**\n * Add a new POST route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n post(pattern, callback) {\n this._add('POST', pattern, callback);\n }\n /**\n * Add a new PATCH route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n patch(pattern, callback) {\n this._add('PATCH', pattern, callback);\n }\n /**\n * Add a new DELETE route\n *\n * @param pattern The pattern to match\n * @param callback The function to call on pattern match\n *\n */\n delete(pattern, callback) {\n this._add('DELETE', pattern, callback);\n }\n /**\n * Route a request.\n *\n * @param req The request to route.\n */\n async route(req) {\n const url = new URL(req.url);\n const { method } = req;\n const { pathname } = url;\n for (const r of this._routes) {\n if (r.method !== method) {\n continue;\n }\n const match = pathname.match(r.pattern);\n if (!match) {\n continue;\n }\n const matches = match.slice(1);\n let body;\n if (r.method === 'PATCH' || r.method === 'PUT' || r.method === 'POST') {\n try {\n body = JSON.parse(await req.text());\n }\n catch {\n body = undefined;\n }\n }\n return r.callback.call(null, {\n pathname,\n body,\n query: Object.fromEntries(url.searchParams),\n }, ...matches);\n }\n throw new Error('Cannot route ' + req.method + ' ' + req.url);\n }\n /**\n * Add a new route.\n *\n * @param method The method\n * @param pattern The pattern\n * @param callback The callback\n */\n _add(method, pattern, callback) {\n if (typeof pattern === 'string') {\n pattern = new RegExp(pattern);\n }\n this._routes.push({\n method,\n pattern,\n callback,\n });\n }\n}\n//# sourceMappingURL=router.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { ServerConnection, ServiceManager } from '@jupyterlab/services';\nimport { Application } from '@lumino/application';\nimport { Stream } from '@lumino/signaling';\nimport { WebSocket } from 'mock-socket';\nimport { Router } from './router';\n/**\n * Mock the Event Manager for now\n */\nclass MockEventManager {\n constructor(options) {\n this._stream = new Stream(this);\n this._serverSettings = options.serverSettings;\n }\n async emit(event) {\n // no-op\n }\n dispose() {\n // no-op\n }\n get isDisposed() {\n return true;\n }\n get stream() {\n return this._stream;\n }\n get serverSettings() {\n return this._serverSettings;\n }\n}\n/**\n * Server is the main application class. It is instantiated once and shared.\n */\nexport class JupyterLiteServer extends Application {\n /**\n * Construct a new JupyterLite object.\n *\n * @param options The instantiation options for a JupyterLiteServer application.\n */\n constructor(options) {\n var _a;\n super(options);\n /**\n * The name of the application.\n */\n this.name = 'JupyterLite Server';\n /**\n * A namespace/prefix plugins may use to denote their provenance.\n */\n this.namespace = this.name;\n /**\n * The version of the application.\n */\n this.version = 'unknown';\n this._router = new Router();\n const serverSettings = {\n ...ServerConnection.makeSettings(),\n WebSocket,\n fetch: (_a = this.fetch.bind(this)) !== null && _a !== void 0 ? _a : undefined,\n };\n this._serviceManager = new ServiceManager({\n standby: 'never',\n serverSettings,\n events: new MockEventManager({ serverSettings }),\n });\n }\n /**\n * Get the underlying `Router` instance.\n */\n get router() {\n return this._router;\n }\n /**\n * Get the underlying lite service manager for this app.\n */\n get serviceManager() {\n return this._serviceManager;\n }\n /**\n * Handle an incoming request from the client.\n *\n * @param req The incoming request\n * @param init The optional init request\n */\n async fetch(req, init) {\n if (!(req instanceof Request)) {\n throw Error('Request info is not a Request');\n }\n return this._router.route(req);\n }\n /**\n * Attach the application shell to the DOM.\n *\n * @param id - The id of the host node for the shell, or `''`.\n *\n * #### Notes\n * For this server application there is no shell to attach\n */\n attachShell(id) {\n // no-op\n }\n /**\n * A method invoked on a window `'resize'` event.\n *\n * #### Notes\n * For this server application there is no shell to update\n */\n evtResize(event) {\n // no-op\n }\n /**\n * Register plugins from a plugin module.\n *\n * @param mod - The plugin module to register.\n */\n registerPluginModule(mod) {\n let data = mod.default;\n // Handle commonjs exports.\n if (!Object.prototype.hasOwnProperty.call(mod, '__esModule')) {\n data = mod;\n }\n if (!Array.isArray(data)) {\n data = [data];\n }\n data.forEach((item) => {\n try {\n this.registerPlugin(item);\n }\n catch (error) {\n console.error(error);\n }\n });\n }\n /**\n * Register the plugins from multiple plugin modules.\n *\n * @param mods - The plugin modules to register.\n */\n registerPluginModules(mods) {\n mods.forEach((mod) => {\n this.registerPluginModule(mod);\n });\n }\n}\n//# sourceMappingURL=app.js.map","import { PromiseDelegate } from '@lumino/coreutils';\nimport { Signal } from '@lumino/signaling';\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { WORKER_NAME } from './tokens';\nexport class ServiceWorkerManager {\n constructor(options) {\n var _a;\n this._registration = null;\n this._registrationChanged = new Signal(this);\n this._ready = new PromiseDelegate();\n const workerUrl = (_a = options === null || options === void 0 ? void 0 : options.workerUrl) !== null && _a !== void 0 ? _a : URLExt.join(PageConfig.getBaseUrl(), WORKER_NAME);\n void this.initialize(workerUrl).catch(console.warn);\n }\n /**\n * A signal emitted when the registration changes.\n */\n get registrationChanged() {\n return this._registrationChanged;\n }\n /**\n * Whether the ServiceWorker is enabled or not.\n */\n get enabled() {\n return this._registration !== null;\n }\n get ready() {\n return this._ready.promise;\n }\n async initialize(workerUrl) {\n const { serviceWorker } = navigator;\n let registration = null;\n if (!serviceWorker) {\n console.warn('ServiceWorkers not supported in this browser');\n }\n else if (serviceWorker.controller) {\n registration =\n (await serviceWorker.getRegistration(serviceWorker.controller.scriptURL)) ||\n null;\n console.info('JupyterLite ServiceWorker was already registered');\n }\n if (!registration && serviceWorker) {\n try {\n console.info('Registering new JupyterLite ServiceWorker', workerUrl);\n registration = await serviceWorker.register(workerUrl);\n console.info('JupyterLite ServiceWorker was sucessfully registered');\n }\n catch (err) {\n console.warn(err);\n console.warn(`JupyterLite ServiceWorker registration unexpectedly failed: ${err}`);\n }\n }\n this.setRegistration(registration);\n if (!registration) {\n this._ready.reject(void 0);\n }\n else {\n this._ready.resolve(void 0);\n }\n }\n setRegistration(registration) {\n this._registration = registration;\n this._registrationChanged.emit(this._registration);\n }\n}\n//# sourceMappingURL=service-manager.js.map","import { Token } from '@lumino/coreutils';\nimport SW_URL from './service-worker?text';\n/**\n * The token for the ServiceWorker.\n */\nexport const IServiceWorkerManager = new Token('@jupyterlite/server-extension:IServiceWorkerManager');\nexport const WORKER_NAME = `${SW_URL}`.split('/').slice(-1)[0];\n//# sourceMappingURL=tokens.js.map","// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for array-specific algorithms.\n */\nvar ArrayExt;\n(function (ArrayExt) {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n function firstIndexOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.firstIndexOf = firstIndexOf;\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n function lastIndexOf(array, value, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (start < stop) {\n span = start + 1 + (n - stop);\n }\n else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.lastIndexOf = lastIndexOf;\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n function findFirstIndex(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findFirstIndex = findFirstIndex;\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n function findLastIndex(array, fn, start = -1, stop = 0) {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let d;\n if (start < stop) {\n d = start + 1 + (n - stop);\n }\n else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n ArrayExt.findLastIndex = findLastIndex;\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n function findFirstValue(array, fn, start = 0, stop = -1) {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findFirstValue = findFirstValue;\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n function findLastValue(array, fn, start = -1, stop = 0) {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n ArrayExt.findLastValue = findLastValue;\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n function lowerBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n }\n else {\n span = half;\n }\n }\n return begin;\n }\n ArrayExt.lowerBound = lowerBound;\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n function upperBound(array, value, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n }\n else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n ArrayExt.upperBound = upperBound;\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n function shallowEqual(a, b, fn) {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n // The array are shallowly equal.\n return true;\n }\n ArrayExt.shallowEqual = shallowEqual;\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n function slice(array, options = {}) {\n // Extract the options.\n let { start, stop, step } = options;\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n // Look up the length of the array.\n let n = array.length;\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n }\n else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n }\n else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n }\n else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n }\n else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n }\n else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n }\n else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n // Compute the sliced result.\n let result = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n // Return the result.\n return result;\n }\n ArrayExt.slice = slice;\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n function move(array, fromIndex, toIndex) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n }\n else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n }\n else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n ArrayExt.move = move;\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n function reverse(array, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n ArrayExt.reverse = reverse;\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n function rotate(array, delta, start = 0, stop = -1) {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n }\n else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n ArrayExt.rotate = rotate;\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n function fill(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let span;\n if (stop < start) {\n span = stop + 1 + (n - start);\n }\n else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n ArrayExt.fill = fill;\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n function insert(array, index, value) {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n }\n else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n ArrayExt.insert = insert;\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n function removeAt(array, index) {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n ArrayExt.removeAt = removeAt;\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n function removeFirstOf(array, value, start = 0, stop = -1) {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeFirstOf = removeFirstOf;\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n function removeLastOf(array, value, start = -1, stop = 0) {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n ArrayExt.removeLastOf = removeLastOf;\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n function removeAllOf(array, value, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n }\n else if (stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllOf = removeAllOf;\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n function removeFirstWhere(array, fn, start = 0, stop = -1) {\n let value;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeFirstWhere = removeFirstWhere;\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n function removeLastWhere(array, fn, start = -1, stop = 0) {\n let value;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n ArrayExt.removeLastWhere = removeLastWhere;\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n function removeAllWhere(array, fn, start = 0, stop = -1) {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n }\n else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n }\n else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n }\n else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n }\n else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n ArrayExt.removeAllWhere = removeAllWhere;\n})(ArrayExt || (ArrayExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nfunction* chain(...objects) {\n for (const object of objects) {\n yield* object;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nfunction* empty() {\n return;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nfunction* enumerate(object, start = 0) {\n for (const value of object) {\n yield [start++, value];\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* filter(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nfunction find(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nfunction findIndex(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nfunction min(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nfunction max(object, fn) {\n let result = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nfunction minmax(object, fn) {\n let empty = true;\n let vmin;\n let vmax;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n }\n else if (fn(value, vmin) < 0) {\n vmin = value;\n }\n else if (fn(value, vmax) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin, vmax];\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nfunction toArray(object) {\n return Array.from(object);\n}\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nfunction toObject(object) {\n const result = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nfunction each(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nfunction every(object, fn) {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nfunction some(object, fn) {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nfunction* map(object, fn) {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nfunction* range(start, stop, step) {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n }\n else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n function rangeLength(start, stop, step) {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n Private.rangeLength = rangeLength;\n})(Private || (Private = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nfunction reduce(object, fn, initial) {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n // Setup the initial accumlated value.\n let accumulator;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n }\n else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n // Iterate the rest of the values, updating the accumulator.\n let next;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n // Return the final accumulated value.\n return accumulator;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nfunction* repeat(value, count) {\n while (0 < count--) {\n yield value;\n }\n}\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nfunction* once(value) {\n yield value;\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nfunction* retro(object) {\n if (typeof object.retro === 'function') {\n yield* object.retro();\n }\n else {\n for (let index = object.length - 1; index > -1; index--) {\n yield object[index];\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nfunction topologicSort(edges) {\n // Setup the shared sorting state.\n let sorted = [];\n let visited = new Set();\n let graph = new Map();\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n // Return the sorted results.\n return sorted;\n // Add an edge to the graph.\n function addEdge(edge) {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n }\n else {\n graph.set(toNode, [fromNode]);\n }\n }\n // Recursively visit the node.\n function visit(node) {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nfunction* stride(object, step) {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * The namespace for string-specific algorithms.\n */\nvar StringExt;\n(function (StringExt) {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n function findIndices(source, query, start = 0) {\n let indices = new Array(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n StringExt.findIndices = findIndices;\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n function matchSumOfSquares(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfSquares = matchSumOfSquares;\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n function matchSumOfDeltas(source, query, start = 0) {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n StringExt.matchSumOfDeltas = matchSumOfDeltas;\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n function highlight(source, indices, fn) {\n // Set up the result array.\n let result = [];\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n // Update the last visited index.\n last = j + 1;\n }\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n // Return the highlighted result.\n return result;\n }\n StringExt.highlight = highlight;\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n function cmp(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n StringExt.cmp = cmp;\n})(StringExt || (StringExt = {}));\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nfunction* take(object, count) {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nfunction* zip(...objects) {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n\nexport { ArrayExt, StringExt, chain, each, empty, enumerate, every, filter, find, findIndex, map, max, min, minmax, once, range, reduce, repeat, retro, some, stride, take, toArray, toObject, topologicSort, zip };\n//# sourceMappingURL=index.es6.js.map\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.lumino_coreutils = {}));\n})(this, (function (exports) { 'use strict';\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for JSON-specific functions.\n */\n exports.JSONExt = void 0;\n (function (JSONExt) {\n /**\n * A shared frozen empty JSONObject\n */\n JSONExt.emptyObject = Object.freeze({});\n /**\n * A shared frozen empty JSONArray\n */\n JSONExt.emptyArray = Object.freeze([]);\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n function isPrimitive(value) {\n return (value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string');\n }\n JSONExt.isPrimitive = isPrimitive;\n function isArray(value) {\n return Array.isArray(value);\n }\n JSONExt.isArray = isArray;\n function isObject(value) {\n return !isPrimitive(value) && !isArray(value);\n }\n JSONExt.isObject = isObject;\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n function deepEqual(first, second) {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(first, second);\n }\n // At this point, they must both be objects.\n return deepObjectEqual(first, second);\n }\n JSONExt.deepEqual = deepEqual;\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n function deepCopy(value) {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n JSONExt.deepCopy = deepCopy;\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n // At this point, the arrays are equal.\n return true;\n }\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(first, second) {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n // At this point, the objects are equal.\n return true;\n }\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value) {\n let result = new Array(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value) {\n let result = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n })(exports.JSONExt || (exports.JSONExt = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\n class MimeData {\n constructor() {\n this._types = [];\n this._values = [];\n }\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types() {\n return this._types.slice();\n }\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime) {\n return this._types.indexOf(mime) !== -1;\n }\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime) {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime, data) {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime) {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n /**\n * Remove all data entries from the dataset.\n */\n clear() {\n this._types.length = 0;\n this._values.length = 0;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\n class PromiseDelegate {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value) {\n let resolve = this._resolve;\n resolve(value);\n }\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason) {\n let reject = this._reject;\n reject(reason);\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\n class Token {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name, description) {\n this.name = name;\n this.description = description !== null && description !== void 0 ? description : '';\n this._tokenStructuralPropertyT = null;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n // Fallback\n function fallbackRandomValues(buffer) {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for random number related functionality.\n */\n exports.Random = void 0;\n (function (Random) {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n Random.getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto = (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer) {\n return crypto.getRandomValues(buffer);\n };\n }\n // Fallback\n return fallbackRandomValues;\n })();\n })(exports.Random || (exports.Random = {}));\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n function uuid4Factory(getRandomValues) {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n // Create a look up table from bytes to hex strings.\n const lut = new Array(256);\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n // Return a function which generates the UUID.\n return function uuid4() {\n // Get a new batch of random values.\n getRandomValues(bytes);\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n // Assemble the UUID string.\n return (lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]);\n };\n }\n\n // Copyright (c) Jupyter Development Team.\n // Distributed under the terms of the Modified BSD License.\n /*-----------------------------------------------------------------------------\n | Copyright (c) 2014-2017, PhosphorJS Contributors\n |\n | Distributed under the terms of the BSD 3-Clause License.\n |\n | The full license is in the file LICENSE, distributed with this software.\n |----------------------------------------------------------------------------*/\n /**\n * The namespace for UUID related functionality.\n */\n exports.UUID = void 0;\n (function (UUID) {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n UUID.uuid4 = uuid4Factory(exports.Random.getRandomValues);\n })(exports.UUID || (exports.UUID = {}));\n\n exports.MimeData = MimeData;\n exports.PromiseDelegate = PromiseDelegate;\n exports.Token = Token;\n\n}));\n//# sourceMappingURL=index.js.map\n","import { find, ArrayExt } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nclass Signal {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender) {\n this.sender = sender;\n }\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot, thisArg) {\n return Private.connect(this, slot, thisArg);\n }\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot, thisArg) {\n return Private.disconnect(this, slot, thisArg);\n }\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args) {\n Private.emit(this, args);\n }\n}\n/**\n * The namespace for the `Signal` class statics.\n */\n(function (Signal) {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectBetween(sender, receiver) {\n Private.disconnectBetween(sender, receiver);\n }\n Signal.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n Private.disconnectSender(sender);\n }\n Signal.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectReceiver(receiver) {\n Private.disconnectReceiver(receiver);\n }\n Signal.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n function disconnectAll(object) {\n Private.disconnectAll(object);\n }\n Signal.disconnectAll = disconnectAll;\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n function clearData(object) {\n Private.disconnectAll(object);\n }\n Signal.clearData = clearData;\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n function getExceptionHandler() {\n return Private.exceptionHandler;\n }\n Signal.getExceptionHandler = getExceptionHandler;\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n function setExceptionHandler(handler) {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n Signal.setExceptionHandler = setExceptionHandler;\n})(Signal || (Signal = {}));\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nclass Stream extends Signal {\n constructor() {\n super(...arguments);\n this._pending = new PromiseDelegate();\n }\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator]() {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n }\n catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args) {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n /**\n * Stop the stream's async iteration.\n */\n stop() {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n}\n/**\n * The namespace for the module implementation details.\n */\nvar Private;\n(function (Private) {\n /**\n * The signal exception handler function.\n */\n Private.exceptionHandler = (err) => {\n console.error(err);\n };\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n function connect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n // Indicate a successful connection.\n return true;\n }\n Private.connect = connect;\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n function disconnect(signal, slot, thisArg) {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver);\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n // Indicate a successful disconnection.\n return true;\n }\n Private.disconnect = disconnect;\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectBetween(sender, receiver) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n Private.disconnectBetween = disconnectBetween;\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n function disconnectSender(sender) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver));\n }\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n Private.disconnectSender = disconnectSender;\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n function disconnectReceiver(receiver) {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n // Clear the connection.\n connection.signal = null;\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender));\n }\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n Private.disconnectReceiver = disconnectReceiver;\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n function disconnectAll(object) {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n Private.disconnectAll = disconnectAll;\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n function emit(signal, args) {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n Private.emit = emit;\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap();\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap();\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set();\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(connections, signal, slot, thisArg) {\n return find(connections, connection => connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg);\n }\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection, args) {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal.sender, args);\n }\n catch (err) {\n Private.exceptionHandler(err);\n }\n }\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array) {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet() {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection) {\n return connection.signal === null;\n }\n})(Private || (Private = {}));\n\nexport { Signal, Stream };\n//# sourceMappingURL=index.es6.js.map\n","'use strict';\n\n/**\n * @param typeMap [Object] Map of MIME type -> Array[extensions]\n * @param ...\n */\nfunction Mime() {\n this._types = Object.create(null);\n this._extensions = Object.create(null);\n\n for (let i = 0; i < arguments.length; i++) {\n this.define(arguments[i]);\n }\n\n this.define = this.define.bind(this);\n this.getType = this.getType.bind(this);\n this.getExtension = this.getExtension.bind(this);\n}\n\n/**\n * Define mimetype -> extension mappings. Each key is a mime-type that maps\n * to an array of extensions associated with the type. The first extension is\n * used as the default extension for the type.\n *\n * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});\n *\n * If a type declares an extension that has already been defined, an error will\n * be thrown. To suppress this error and force the extension to be associated\n * with the new type, pass `force`=true. Alternatively, you may prefix the\n * extension with \"*\" to map the type to extension, without mapping the\n * extension to the type.\n *\n * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});\n *\n *\n * @param map (Object) type definitions\n * @param force (Boolean) if true, force overriding of existing definitions\n */\nMime.prototype.define = function(typeMap, force) {\n for (let type in typeMap) {\n let extensions = typeMap[type].map(function(t) {\n return t.toLowerCase();\n });\n type = type.toLowerCase();\n\n for (let i = 0; i < extensions.length; i++) {\n const ext = extensions[i];\n\n // '*' prefix = not the preferred type for this extension. So fixup the\n // extension, and skip it.\n if (ext[0] === '*') {\n continue;\n }\n\n if (!force && (ext in this._types)) {\n throw new Error(\n 'Attempt to change mapping for \"' + ext +\n '\" extension from \"' + this._types[ext] + '\" to \"' + type +\n '\". Pass `force=true` to allow this, otherwise remove \"' + ext +\n '\" from the list of extensions for \"' + type + '\".'\n );\n }\n\n this._types[ext] = type;\n }\n\n // Use first extension as default\n if (force || !this._extensions[type]) {\n const ext = extensions[0];\n this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);\n }\n }\n};\n\n/**\n * Lookup a mime type based on extension\n */\nMime.prototype.getType = function(path) {\n path = String(path);\n let last = path.replace(/^.*[/\\\\]/, '').toLowerCase();\n let ext = last.replace(/^.*\\./, '').toLowerCase();\n\n let hasPath = last.length < path.length;\n let hasDot = ext.length < last.length - 1;\n\n return (hasDot || !hasPath) && this._types[ext] || null;\n};\n\n/**\n * Return file extension associated with a mime type\n */\nMime.prototype.getExtension = function(type) {\n type = /^\\s*([^;\\s]*)/.test(type) && RegExp.$1;\n return type && this._extensions[type.toLowerCase()] || null;\n};\n\nmodule.exports = Mime;\n","'use strict';\n\nlet Mime = require('./Mime');\nmodule.exports = new Mime(require('./types/standard'), require('./types/other'));\n","module.exports = {\"application/prs.cww\":[\"cww\"],\"application/vnd.1000minds.decision-model+xml\":[\"1km\"],\"application/vnd.3gpp.pic-bw-large\":[\"plb\"],\"application/vnd.3gpp.pic-bw-small\":[\"psb\"],\"application/vnd.3gpp.pic-bw-var\":[\"pvb\"],\"application/vnd.3gpp2.tcap\":[\"tcap\"],\"application/vnd.3m.post-it-notes\":[\"pwn\"],\"application/vnd.accpac.simply.aso\":[\"aso\"],\"application/vnd.accpac.simply.imp\":[\"imp\"],\"application/vnd.acucobol\":[\"acu\"],\"application/vnd.acucorp\":[\"atc\",\"acutc\"],\"application/vnd.adobe.air-application-installer-package+zip\":[\"air\"],\"application/vnd.adobe.formscentral.fcdt\":[\"fcdt\"],\"application/vnd.adobe.fxp\":[\"fxp\",\"fxpl\"],\"application/vnd.adobe.xdp+xml\":[\"xdp\"],\"application/vnd.adobe.xfdf\":[\"xfdf\"],\"application/vnd.ahead.space\":[\"ahead\"],\"application/vnd.airzip.filesecure.azf\":[\"azf\"],\"application/vnd.airzip.filesecure.azs\":[\"azs\"],\"application/vnd.amazon.ebook\":[\"azw\"],\"application/vnd.americandynamics.acc\":[\"acc\"],\"application/vnd.amiga.ami\":[\"ami\"],\"application/vnd.android.package-archive\":[\"apk\"],\"application/vnd.anser-web-certificate-issue-initiation\":[\"cii\"],\"application/vnd.anser-web-funds-transfer-initiation\":[\"fti\"],\"application/vnd.antix.game-component\":[\"atx\"],\"application/vnd.apple.installer+xml\":[\"mpkg\"],\"application/vnd.apple.keynote\":[\"key\"],\"application/vnd.apple.mpegurl\":[\"m3u8\"],\"application/vnd.apple.numbers\":[\"numbers\"],\"application/vnd.apple.pages\":[\"pages\"],\"application/vnd.apple.pkpass\":[\"pkpass\"],\"application/vnd.aristanetworks.swi\":[\"swi\"],\"application/vnd.astraea-software.iota\":[\"iota\"],\"application/vnd.audiograph\":[\"aep\"],\"application/vnd.balsamiq.bmml+xml\":[\"bmml\"],\"application/vnd.blueice.multipass\":[\"mpm\"],\"application/vnd.bmi\":[\"bmi\"],\"application/vnd.businessobjects\":[\"rep\"],\"application/vnd.chemdraw+xml\":[\"cdxml\"],\"application/vnd.chipnuts.karaoke-mmd\":[\"mmd\"],\"application/vnd.cinderella\":[\"cdy\"],\"application/vnd.citationstyles.style+xml\":[\"csl\"],\"application/vnd.claymore\":[\"cla\"],\"application/vnd.cloanto.rp9\":[\"rp9\"],\"application/vnd.clonk.c4group\":[\"c4g\",\"c4d\",\"c4f\",\"c4p\",\"c4u\"],\"application/vnd.cluetrust.cartomobile-config\":[\"c11amc\"],\"application/vnd.cluetrust.cartomobile-config-pkg\":[\"c11amz\"],\"application/vnd.commonspace\":[\"csp\"],\"application/vnd.contact.cmsg\":[\"cdbcmsg\"],\"application/vnd.cosmocaller\":[\"cmc\"],\"application/vnd.crick.clicker\":[\"clkx\"],\"application/vnd.crick.clicker.keyboard\":[\"clkk\"],\"application/vnd.crick.clicker.palette\":[\"clkp\"],\"application/vnd.crick.clicker.template\":[\"clkt\"],\"application/vnd.crick.clicker.wordbank\":[\"clkw\"],\"application/vnd.criticaltools.wbs+xml\":[\"wbs\"],\"application/vnd.ctc-posml\":[\"pml\"],\"application/vnd.cups-ppd\":[\"ppd\"],\"application/vnd.curl.car\":[\"car\"],\"application/vnd.curl.pcurl\":[\"pcurl\"],\"application/vnd.dart\":[\"dart\"],\"application/vnd.data-vision.rdz\":[\"rdz\"],\"application/vnd.dbf\":[\"dbf\"],\"application/vnd.dece.data\":[\"uvf\",\"uvvf\",\"uvd\",\"uvvd\"],\"application/vnd.dece.ttml+xml\":[\"uvt\",\"uvvt\"],\"application/vnd.dece.unspecified\":[\"uvx\",\"uvvx\"],\"application/vnd.dece.zip\":[\"uvz\",\"uvvz\"],\"application/vnd.denovo.fcselayout-link\":[\"fe_launch\"],\"application/vnd.dna\":[\"dna\"],\"application/vnd.dolby.mlp\":[\"mlp\"],\"application/vnd.dpgraph\":[\"dpg\"],\"application/vnd.dreamfactory\":[\"dfac\"],\"application/vnd.ds-keypoint\":[\"kpxx\"],\"application/vnd.dvb.ait\":[\"ait\"],\"application/vnd.dvb.service\":[\"svc\"],\"application/vnd.dynageo\":[\"geo\"],\"application/vnd.ecowin.chart\":[\"mag\"],\"application/vnd.enliven\":[\"nml\"],\"application/vnd.epson.esf\":[\"esf\"],\"application/vnd.epson.msf\":[\"msf\"],\"application/vnd.epson.quickanime\":[\"qam\"],\"application/vnd.epson.salt\":[\"slt\"],\"application/vnd.epson.ssf\":[\"ssf\"],\"application/vnd.eszigno3+xml\":[\"es3\",\"et3\"],\"application/vnd.ezpix-album\":[\"ez2\"],\"application/vnd.ezpix-package\":[\"ez3\"],\"application/vnd.fdf\":[\"fdf\"],\"application/vnd.fdsn.mseed\":[\"mseed\"],\"application/vnd.fdsn.seed\":[\"seed\",\"dataless\"],\"application/vnd.flographit\":[\"gph\"],\"application/vnd.fluxtime.clip\":[\"ftc\"],\"application/vnd.framemaker\":[\"fm\",\"frame\",\"maker\",\"book\"],\"application/vnd.frogans.fnc\":[\"fnc\"],\"application/vnd.frogans.ltf\":[\"ltf\"],\"application/vnd.fsc.weblaunch\":[\"fsc\"],\"application/vnd.fujitsu.oasys\":[\"oas\"],\"application/vnd.fujitsu.oasys2\":[\"oa2\"],\"application/vnd.fujitsu.oasys3\":[\"oa3\"],\"application/vnd.fujitsu.oasysgp\":[\"fg5\"],\"application/vnd.fujitsu.oasysprs\":[\"bh2\"],\"application/vnd.fujixerox.ddd\":[\"ddd\"],\"application/vnd.fujixerox.docuworks\":[\"xdw\"],\"application/vnd.fujixerox.docuworks.binder\":[\"xbd\"],\"application/vnd.fuzzysheet\":[\"fzs\"],\"application/vnd.genomatix.tuxedo\":[\"txd\"],\"application/vnd.geogebra.file\":[\"ggb\"],\"application/vnd.geogebra.tool\":[\"ggt\"],\"application/vnd.geometry-explorer\":[\"gex\",\"gre\"],\"application/vnd.geonext\":[\"gxt\"],\"application/vnd.geoplan\":[\"g2w\"],\"application/vnd.geospace\":[\"g3w\"],\"application/vnd.gmx\":[\"gmx\"],\"application/vnd.google-apps.document\":[\"gdoc\"],\"application/vnd.google-apps.presentation\":[\"gslides\"],\"application/vnd.google-apps.spreadsheet\":[\"gsheet\"],\"application/vnd.google-earth.kml+xml\":[\"kml\"],\"application/vnd.google-earth.kmz\":[\"kmz\"],\"application/vnd.grafeq\":[\"gqf\",\"gqs\"],\"application/vnd.groove-account\":[\"gac\"],\"application/vnd.groove-help\":[\"ghf\"],\"application/vnd.groove-identity-message\":[\"gim\"],\"application/vnd.groove-injector\":[\"grv\"],\"application/vnd.groove-tool-message\":[\"gtm\"],\"application/vnd.groove-tool-template\":[\"tpl\"],\"application/vnd.groove-vcard\":[\"vcg\"],\"application/vnd.hal+xml\":[\"hal\"],\"application/vnd.handheld-entertainment+xml\":[\"zmm\"],\"application/vnd.hbci\":[\"hbci\"],\"application/vnd.hhe.lesson-player\":[\"les\"],\"application/vnd.hp-hpgl\":[\"hpgl\"],\"application/vnd.hp-hpid\":[\"hpid\"],\"application/vnd.hp-hps\":[\"hps\"],\"application/vnd.hp-jlyt\":[\"jlt\"],\"application/vnd.hp-pcl\":[\"pcl\"],\"application/vnd.hp-pclxl\":[\"pclxl\"],\"application/vnd.hydrostatix.sof-data\":[\"sfd-hdstx\"],\"application/vnd.ibm.minipay\":[\"mpy\"],\"application/vnd.ibm.modcap\":[\"afp\",\"listafp\",\"list3820\"],\"application/vnd.ibm.rights-management\":[\"irm\"],\"application/vnd.ibm.secure-container\":[\"sc\"],\"application/vnd.iccprofile\":[\"icc\",\"icm\"],\"application/vnd.igloader\":[\"igl\"],\"application/vnd.immervision-ivp\":[\"ivp\"],\"application/vnd.immervision-ivu\":[\"ivu\"],\"application/vnd.insors.igm\":[\"igm\"],\"application/vnd.intercon.formnet\":[\"xpw\",\"xpx\"],\"application/vnd.intergeo\":[\"i2g\"],\"application/vnd.intu.qbo\":[\"qbo\"],\"application/vnd.intu.qfx\":[\"qfx\"],\"application/vnd.ipunplugged.rcprofile\":[\"rcprofile\"],\"application/vnd.irepository.package+xml\":[\"irp\"],\"application/vnd.is-xpr\":[\"xpr\"],\"application/vnd.isac.fcs\":[\"fcs\"],\"application/vnd.jam\":[\"jam\"],\"application/vnd.jcp.javame.midlet-rms\":[\"rms\"],\"application/vnd.jisp\":[\"jisp\"],\"application/vnd.joost.joda-archive\":[\"joda\"],\"application/vnd.kahootz\":[\"ktz\",\"ktr\"],\"application/vnd.kde.karbon\":[\"karbon\"],\"application/vnd.kde.kchart\":[\"chrt\"],\"application/vnd.kde.kformula\":[\"kfo\"],\"application/vnd.kde.kivio\":[\"flw\"],\"application/vnd.kde.kontour\":[\"kon\"],\"application/vnd.kde.kpresenter\":[\"kpr\",\"kpt\"],\"application/vnd.kde.kspread\":[\"ksp\"],\"application/vnd.kde.kword\":[\"kwd\",\"kwt\"],\"application/vnd.kenameaapp\":[\"htke\"],\"application/vnd.kidspiration\":[\"kia\"],\"application/vnd.kinar\":[\"kne\",\"knp\"],\"application/vnd.koan\":[\"skp\",\"skd\",\"skt\",\"skm\"],\"application/vnd.kodak-descriptor\":[\"sse\"],\"application/vnd.las.las+xml\":[\"lasxml\"],\"application/vnd.llamagraphics.life-balance.desktop\":[\"lbd\"],\"application/vnd.llamagraphics.life-balance.exchange+xml\":[\"lbe\"],\"application/vnd.lotus-1-2-3\":[\"123\"],\"application/vnd.lotus-approach\":[\"apr\"],\"application/vnd.lotus-freelance\":[\"pre\"],\"application/vnd.lotus-notes\":[\"nsf\"],\"application/vnd.lotus-organizer\":[\"org\"],\"application/vnd.lotus-screencam\":[\"scm\"],\"application/vnd.lotus-wordpro\":[\"lwp\"],\"application/vnd.macports.portpkg\":[\"portpkg\"],\"application/vnd.mapbox-vector-tile\":[\"mvt\"],\"application/vnd.mcd\":[\"mcd\"],\"application/vnd.medcalcdata\":[\"mc1\"],\"application/vnd.mediastation.cdkey\":[\"cdkey\"],\"application/vnd.mfer\":[\"mwf\"],\"application/vnd.mfmp\":[\"mfm\"],\"application/vnd.micrografx.flo\":[\"flo\"],\"application/vnd.micrografx.igx\":[\"igx\"],\"application/vnd.mif\":[\"mif\"],\"application/vnd.mobius.daf\":[\"daf\"],\"application/vnd.mobius.dis\":[\"dis\"],\"application/vnd.mobius.mbk\":[\"mbk\"],\"application/vnd.mobius.mqy\":[\"mqy\"],\"application/vnd.mobius.msl\":[\"msl\"],\"application/vnd.mobius.plc\":[\"plc\"],\"application/vnd.mobius.txf\":[\"txf\"],\"application/vnd.mophun.application\":[\"mpn\"],\"application/vnd.mophun.certificate\":[\"mpc\"],\"application/vnd.mozilla.xul+xml\":[\"xul\"],\"application/vnd.ms-artgalry\":[\"cil\"],\"application/vnd.ms-cab-compressed\":[\"cab\"],\"application/vnd.ms-excel\":[\"xls\",\"xlm\",\"xla\",\"xlc\",\"xlt\",\"xlw\"],\"application/vnd.ms-excel.addin.macroenabled.12\":[\"xlam\"],\"application/vnd.ms-excel.sheet.binary.macroenabled.12\":[\"xlsb\"],\"application/vnd.ms-excel.sheet.macroenabled.12\":[\"xlsm\"],\"application/vnd.ms-excel.template.macroenabled.12\":[\"xltm\"],\"application/vnd.ms-fontobject\":[\"eot\"],\"application/vnd.ms-htmlhelp\":[\"chm\"],\"application/vnd.ms-ims\":[\"ims\"],\"application/vnd.ms-lrm\":[\"lrm\"],\"application/vnd.ms-officetheme\":[\"thmx\"],\"application/vnd.ms-outlook\":[\"msg\"],\"application/vnd.ms-pki.seccat\":[\"cat\"],\"application/vnd.ms-pki.stl\":[\"*stl\"],\"application/vnd.ms-powerpoint\":[\"ppt\",\"pps\",\"pot\"],\"application/vnd.ms-powerpoint.addin.macroenabled.12\":[\"ppam\"],\"application/vnd.ms-powerpoint.presentation.macroenabled.12\":[\"pptm\"],\"application/vnd.ms-powerpoint.slide.macroenabled.12\":[\"sldm\"],\"application/vnd.ms-powerpoint.slideshow.macroenabled.12\":[\"ppsm\"],\"application/vnd.ms-powerpoint.template.macroenabled.12\":[\"potm\"],\"application/vnd.ms-project\":[\"mpp\",\"mpt\"],\"application/vnd.ms-word.document.macroenabled.12\":[\"docm\"],\"application/vnd.ms-word.template.macroenabled.12\":[\"dotm\"],\"application/vnd.ms-works\":[\"wps\",\"wks\",\"wcm\",\"wdb\"],\"application/vnd.ms-wpl\":[\"wpl\"],\"application/vnd.ms-xpsdocument\":[\"xps\"],\"application/vnd.mseq\":[\"mseq\"],\"application/vnd.musician\":[\"mus\"],\"application/vnd.muvee.style\":[\"msty\"],\"application/vnd.mynfc\":[\"taglet\"],\"application/vnd.neurolanguage.nlu\":[\"nlu\"],\"application/vnd.nitf\":[\"ntf\",\"nitf\"],\"application/vnd.noblenet-directory\":[\"nnd\"],\"application/vnd.noblenet-sealer\":[\"nns\"],\"application/vnd.noblenet-web\":[\"nnw\"],\"application/vnd.nokia.n-gage.ac+xml\":[\"*ac\"],\"application/vnd.nokia.n-gage.data\":[\"ngdat\"],\"application/vnd.nokia.n-gage.symbian.install\":[\"n-gage\"],\"application/vnd.nokia.radio-preset\":[\"rpst\"],\"application/vnd.nokia.radio-presets\":[\"rpss\"],\"application/vnd.novadigm.edm\":[\"edm\"],\"application/vnd.novadigm.edx\":[\"edx\"],\"application/vnd.novadigm.ext\":[\"ext\"],\"application/vnd.oasis.opendocument.chart\":[\"odc\"],\"application/vnd.oasis.opendocument.chart-template\":[\"otc\"],\"application/vnd.oasis.opendocument.database\":[\"odb\"],\"application/vnd.oasis.opendocument.formula\":[\"odf\"],\"application/vnd.oasis.opendocument.formula-template\":[\"odft\"],\"application/vnd.oasis.opendocument.graphics\":[\"odg\"],\"application/vnd.oasis.opendocument.graphics-template\":[\"otg\"],\"application/vnd.oasis.opendocument.image\":[\"odi\"],\"application/vnd.oasis.opendocument.image-template\":[\"oti\"],\"application/vnd.oasis.opendocument.presentation\":[\"odp\"],\"application/vnd.oasis.opendocument.presentation-template\":[\"otp\"],\"application/vnd.oasis.opendocument.spreadsheet\":[\"ods\"],\"application/vnd.oasis.opendocument.spreadsheet-template\":[\"ots\"],\"application/vnd.oasis.opendocument.text\":[\"odt\"],\"application/vnd.oasis.opendocument.text-master\":[\"odm\"],\"application/vnd.oasis.opendocument.text-template\":[\"ott\"],\"application/vnd.oasis.opendocument.text-web\":[\"oth\"],\"application/vnd.olpc-sugar\":[\"xo\"],\"application/vnd.oma.dd2+xml\":[\"dd2\"],\"application/vnd.openblox.game+xml\":[\"obgx\"],\"application/vnd.openofficeorg.extension\":[\"oxt\"],\"application/vnd.openstreetmap.data+xml\":[\"osm\"],\"application/vnd.openxmlformats-officedocument.presentationml.presentation\":[\"pptx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slide\":[\"sldx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\":[\"ppsx\"],\"application/vnd.openxmlformats-officedocument.presentationml.template\":[\"potx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":[\"xlsx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\":[\"xltx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":[\"docx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\":[\"dotx\"],\"application/vnd.osgeo.mapguide.package\":[\"mgp\"],\"application/vnd.osgi.dp\":[\"dp\"],\"application/vnd.osgi.subsystem\":[\"esa\"],\"application/vnd.palm\":[\"pdb\",\"pqa\",\"oprc\"],\"application/vnd.pawaafile\":[\"paw\"],\"application/vnd.pg.format\":[\"str\"],\"application/vnd.pg.osasli\":[\"ei6\"],\"application/vnd.picsel\":[\"efif\"],\"application/vnd.pmi.widget\":[\"wg\"],\"application/vnd.pocketlearn\":[\"plf\"],\"application/vnd.powerbuilder6\":[\"pbd\"],\"application/vnd.previewsystems.box\":[\"box\"],\"application/vnd.proteus.magazine\":[\"mgz\"],\"application/vnd.publishare-delta-tree\":[\"qps\"],\"application/vnd.pvi.ptid1\":[\"ptid\"],\"application/vnd.quark.quarkxpress\":[\"qxd\",\"qxt\",\"qwd\",\"qwt\",\"qxl\",\"qxb\"],\"application/vnd.rar\":[\"rar\"],\"application/vnd.realvnc.bed\":[\"bed\"],\"application/vnd.recordare.musicxml\":[\"mxl\"],\"application/vnd.recordare.musicxml+xml\":[\"musicxml\"],\"application/vnd.rig.cryptonote\":[\"cryptonote\"],\"application/vnd.rim.cod\":[\"cod\"],\"application/vnd.rn-realmedia\":[\"rm\"],\"application/vnd.rn-realmedia-vbr\":[\"rmvb\"],\"application/vnd.route66.link66+xml\":[\"link66\"],\"application/vnd.sailingtracker.track\":[\"st\"],\"application/vnd.seemail\":[\"see\"],\"application/vnd.sema\":[\"sema\"],\"application/vnd.semd\":[\"semd\"],\"application/vnd.semf\":[\"semf\"],\"application/vnd.shana.informed.formdata\":[\"ifm\"],\"application/vnd.shana.informed.formtemplate\":[\"itp\"],\"application/vnd.shana.informed.interchange\":[\"iif\"],\"application/vnd.shana.informed.package\":[\"ipk\"],\"application/vnd.simtech-mindmapper\":[\"twd\",\"twds\"],\"application/vnd.smaf\":[\"mmf\"],\"application/vnd.smart.teacher\":[\"teacher\"],\"application/vnd.software602.filler.form+xml\":[\"fo\"],\"application/vnd.solent.sdkm+xml\":[\"sdkm\",\"sdkd\"],\"application/vnd.spotfire.dxp\":[\"dxp\"],\"application/vnd.spotfire.sfs\":[\"sfs\"],\"application/vnd.stardivision.calc\":[\"sdc\"],\"application/vnd.stardivision.draw\":[\"sda\"],\"application/vnd.stardivision.impress\":[\"sdd\"],\"application/vnd.stardivision.math\":[\"smf\"],\"application/vnd.stardivision.writer\":[\"sdw\",\"vor\"],\"application/vnd.stardivision.writer-global\":[\"sgl\"],\"application/vnd.stepmania.package\":[\"smzip\"],\"application/vnd.stepmania.stepchart\":[\"sm\"],\"application/vnd.sun.wadl+xml\":[\"wadl\"],\"application/vnd.sun.xml.calc\":[\"sxc\"],\"application/vnd.sun.xml.calc.template\":[\"stc\"],\"application/vnd.sun.xml.draw\":[\"sxd\"],\"application/vnd.sun.xml.draw.template\":[\"std\"],\"application/vnd.sun.xml.impress\":[\"sxi\"],\"application/vnd.sun.xml.impress.template\":[\"sti\"],\"application/vnd.sun.xml.math\":[\"sxm\"],\"application/vnd.sun.xml.writer\":[\"sxw\"],\"application/vnd.sun.xml.writer.global\":[\"sxg\"],\"application/vnd.sun.xml.writer.template\":[\"stw\"],\"application/vnd.sus-calendar\":[\"sus\",\"susp\"],\"application/vnd.svd\":[\"svd\"],\"application/vnd.symbian.install\":[\"sis\",\"sisx\"],\"application/vnd.syncml+xml\":[\"xsm\"],\"application/vnd.syncml.dm+wbxml\":[\"bdm\"],\"application/vnd.syncml.dm+xml\":[\"xdm\"],\"application/vnd.syncml.dmddf+xml\":[\"ddf\"],\"application/vnd.tao.intent-module-archive\":[\"tao\"],\"application/vnd.tcpdump.pcap\":[\"pcap\",\"cap\",\"dmp\"],\"application/vnd.tmobile-livetv\":[\"tmo\"],\"application/vnd.trid.tpt\":[\"tpt\"],\"application/vnd.triscape.mxs\":[\"mxs\"],\"application/vnd.trueapp\":[\"tra\"],\"application/vnd.ufdl\":[\"ufd\",\"ufdl\"],\"application/vnd.uiq.theme\":[\"utz\"],\"application/vnd.umajin\":[\"umj\"],\"application/vnd.unity\":[\"unityweb\"],\"application/vnd.uoml+xml\":[\"uoml\"],\"application/vnd.vcx\":[\"vcx\"],\"application/vnd.visio\":[\"vsd\",\"vst\",\"vss\",\"vsw\"],\"application/vnd.visionary\":[\"vis\"],\"application/vnd.vsf\":[\"vsf\"],\"application/vnd.wap.wbxml\":[\"wbxml\"],\"application/vnd.wap.wmlc\":[\"wmlc\"],\"application/vnd.wap.wmlscriptc\":[\"wmlsc\"],\"application/vnd.webturbo\":[\"wtb\"],\"application/vnd.wolfram.player\":[\"nbp\"],\"application/vnd.wordperfect\":[\"wpd\"],\"application/vnd.wqd\":[\"wqd\"],\"application/vnd.wt.stf\":[\"stf\"],\"application/vnd.xara\":[\"xar\"],\"application/vnd.xfdl\":[\"xfdl\"],\"application/vnd.yamaha.hv-dic\":[\"hvd\"],\"application/vnd.yamaha.hv-script\":[\"hvs\"],\"application/vnd.yamaha.hv-voice\":[\"hvp\"],\"application/vnd.yamaha.openscoreformat\":[\"osf\"],\"application/vnd.yamaha.openscoreformat.osfpvg+xml\":[\"osfpvg\"],\"application/vnd.yamaha.smaf-audio\":[\"saf\"],\"application/vnd.yamaha.smaf-phrase\":[\"spf\"],\"application/vnd.yellowriver-custom-menu\":[\"cmp\"],\"application/vnd.zul\":[\"zir\",\"zirz\"],\"application/vnd.zzazz.deck+xml\":[\"zaz\"],\"application/x-7z-compressed\":[\"7z\"],\"application/x-abiword\":[\"abw\"],\"application/x-ace-compressed\":[\"ace\"],\"application/x-apple-diskimage\":[\"*dmg\"],\"application/x-arj\":[\"arj\"],\"application/x-authorware-bin\":[\"aab\",\"x32\",\"u32\",\"vox\"],\"application/x-authorware-map\":[\"aam\"],\"application/x-authorware-seg\":[\"aas\"],\"application/x-bcpio\":[\"bcpio\"],\"application/x-bdoc\":[\"*bdoc\"],\"application/x-bittorrent\":[\"torrent\"],\"application/x-blorb\":[\"blb\",\"blorb\"],\"application/x-bzip\":[\"bz\"],\"application/x-bzip2\":[\"bz2\",\"boz\"],\"application/x-cbr\":[\"cbr\",\"cba\",\"cbt\",\"cbz\",\"cb7\"],\"application/x-cdlink\":[\"vcd\"],\"application/x-cfs-compressed\":[\"cfs\"],\"application/x-chat\":[\"chat\"],\"application/x-chess-pgn\":[\"pgn\"],\"application/x-chrome-extension\":[\"crx\"],\"application/x-cocoa\":[\"cco\"],\"application/x-conference\":[\"nsc\"],\"application/x-cpio\":[\"cpio\"],\"application/x-csh\":[\"csh\"],\"application/x-debian-package\":[\"*deb\",\"udeb\"],\"application/x-dgc-compressed\":[\"dgc\"],\"application/x-director\":[\"dir\",\"dcr\",\"dxr\",\"cst\",\"cct\",\"cxt\",\"w3d\",\"fgd\",\"swa\"],\"application/x-doom\":[\"wad\"],\"application/x-dtbncx+xml\":[\"ncx\"],\"application/x-dtbook+xml\":[\"dtb\"],\"application/x-dtbresource+xml\":[\"res\"],\"application/x-dvi\":[\"dvi\"],\"application/x-envoy\":[\"evy\"],\"application/x-eva\":[\"eva\"],\"application/x-font-bdf\":[\"bdf\"],\"application/x-font-ghostscript\":[\"gsf\"],\"application/x-font-linux-psf\":[\"psf\"],\"application/x-font-pcf\":[\"pcf\"],\"application/x-font-snf\":[\"snf\"],\"application/x-font-type1\":[\"pfa\",\"pfb\",\"pfm\",\"afm\"],\"application/x-freearc\":[\"arc\"],\"application/x-futuresplash\":[\"spl\"],\"application/x-gca-compressed\":[\"gca\"],\"application/x-glulx\":[\"ulx\"],\"application/x-gnumeric\":[\"gnumeric\"],\"application/x-gramps-xml\":[\"gramps\"],\"application/x-gtar\":[\"gtar\"],\"application/x-hdf\":[\"hdf\"],\"application/x-httpd-php\":[\"php\"],\"application/x-install-instructions\":[\"install\"],\"application/x-iso9660-image\":[\"*iso\"],\"application/x-iwork-keynote-sffkey\":[\"*key\"],\"application/x-iwork-numbers-sffnumbers\":[\"*numbers\"],\"application/x-iwork-pages-sffpages\":[\"*pages\"],\"application/x-java-archive-diff\":[\"jardiff\"],\"application/x-java-jnlp-file\":[\"jnlp\"],\"application/x-keepass2\":[\"kdbx\"],\"application/x-latex\":[\"latex\"],\"application/x-lua-bytecode\":[\"luac\"],\"application/x-lzh-compressed\":[\"lzh\",\"lha\"],\"application/x-makeself\":[\"run\"],\"application/x-mie\":[\"mie\"],\"application/x-mobipocket-ebook\":[\"prc\",\"mobi\"],\"application/x-ms-application\":[\"application\"],\"application/x-ms-shortcut\":[\"lnk\"],\"application/x-ms-wmd\":[\"wmd\"],\"application/x-ms-wmz\":[\"wmz\"],\"application/x-ms-xbap\":[\"xbap\"],\"application/x-msaccess\":[\"mdb\"],\"application/x-msbinder\":[\"obd\"],\"application/x-mscardfile\":[\"crd\"],\"application/x-msclip\":[\"clp\"],\"application/x-msdos-program\":[\"*exe\"],\"application/x-msdownload\":[\"*exe\",\"*dll\",\"com\",\"bat\",\"*msi\"],\"application/x-msmediaview\":[\"mvb\",\"m13\",\"m14\"],\"application/x-msmetafile\":[\"*wmf\",\"*wmz\",\"*emf\",\"emz\"],\"application/x-msmoney\":[\"mny\"],\"application/x-mspublisher\":[\"pub\"],\"application/x-msschedule\":[\"scd\"],\"application/x-msterminal\":[\"trm\"],\"application/x-mswrite\":[\"wri\"],\"application/x-netcdf\":[\"nc\",\"cdf\"],\"application/x-ns-proxy-autoconfig\":[\"pac\"],\"application/x-nzb\":[\"nzb\"],\"application/x-perl\":[\"pl\",\"pm\"],\"application/x-pilot\":[\"*prc\",\"*pdb\"],\"application/x-pkcs12\":[\"p12\",\"pfx\"],\"application/x-pkcs7-certificates\":[\"p7b\",\"spc\"],\"application/x-pkcs7-certreqresp\":[\"p7r\"],\"application/x-rar-compressed\":[\"*rar\"],\"application/x-redhat-package-manager\":[\"rpm\"],\"application/x-research-info-systems\":[\"ris\"],\"application/x-sea\":[\"sea\"],\"application/x-sh\":[\"sh\"],\"application/x-shar\":[\"shar\"],\"application/x-shockwave-flash\":[\"swf\"],\"application/x-silverlight-app\":[\"xap\"],\"application/x-sql\":[\"sql\"],\"application/x-stuffit\":[\"sit\"],\"application/x-stuffitx\":[\"sitx\"],\"application/x-subrip\":[\"srt\"],\"application/x-sv4cpio\":[\"sv4cpio\"],\"application/x-sv4crc\":[\"sv4crc\"],\"application/x-t3vm-image\":[\"t3\"],\"application/x-tads\":[\"gam\"],\"application/x-tar\":[\"tar\"],\"application/x-tcl\":[\"tcl\",\"tk\"],\"application/x-tex\":[\"tex\"],\"application/x-tex-tfm\":[\"tfm\"],\"application/x-texinfo\":[\"texinfo\",\"texi\"],\"application/x-tgif\":[\"*obj\"],\"application/x-ustar\":[\"ustar\"],\"application/x-virtualbox-hdd\":[\"hdd\"],\"application/x-virtualbox-ova\":[\"ova\"],\"application/x-virtualbox-ovf\":[\"ovf\"],\"application/x-virtualbox-vbox\":[\"vbox\"],\"application/x-virtualbox-vbox-extpack\":[\"vbox-extpack\"],\"application/x-virtualbox-vdi\":[\"vdi\"],\"application/x-virtualbox-vhd\":[\"vhd\"],\"application/x-virtualbox-vmdk\":[\"vmdk\"],\"application/x-wais-source\":[\"src\"],\"application/x-web-app-manifest+json\":[\"webapp\"],\"application/x-x509-ca-cert\":[\"der\",\"crt\",\"pem\"],\"application/x-xfig\":[\"fig\"],\"application/x-xliff+xml\":[\"*xlf\"],\"application/x-xpinstall\":[\"xpi\"],\"application/x-xz\":[\"xz\"],\"application/x-zmachine\":[\"z1\",\"z2\",\"z3\",\"z4\",\"z5\",\"z6\",\"z7\",\"z8\"],\"audio/vnd.dece.audio\":[\"uva\",\"uvva\"],\"audio/vnd.digital-winds\":[\"eol\"],\"audio/vnd.dra\":[\"dra\"],\"audio/vnd.dts\":[\"dts\"],\"audio/vnd.dts.hd\":[\"dtshd\"],\"audio/vnd.lucent.voice\":[\"lvp\"],\"audio/vnd.ms-playready.media.pya\":[\"pya\"],\"audio/vnd.nuera.ecelp4800\":[\"ecelp4800\"],\"audio/vnd.nuera.ecelp7470\":[\"ecelp7470\"],\"audio/vnd.nuera.ecelp9600\":[\"ecelp9600\"],\"audio/vnd.rip\":[\"rip\"],\"audio/x-aac\":[\"aac\"],\"audio/x-aiff\":[\"aif\",\"aiff\",\"aifc\"],\"audio/x-caf\":[\"caf\"],\"audio/x-flac\":[\"flac\"],\"audio/x-m4a\":[\"*m4a\"],\"audio/x-matroska\":[\"mka\"],\"audio/x-mpegurl\":[\"m3u\"],\"audio/x-ms-wax\":[\"wax\"],\"audio/x-ms-wma\":[\"wma\"],\"audio/x-pn-realaudio\":[\"ram\",\"ra\"],\"audio/x-pn-realaudio-plugin\":[\"rmp\"],\"audio/x-realaudio\":[\"*ra\"],\"audio/x-wav\":[\"*wav\"],\"chemical/x-cdx\":[\"cdx\"],\"chemical/x-cif\":[\"cif\"],\"chemical/x-cmdf\":[\"cmdf\"],\"chemical/x-cml\":[\"cml\"],\"chemical/x-csml\":[\"csml\"],\"chemical/x-xyz\":[\"xyz\"],\"image/prs.btif\":[\"btif\"],\"image/prs.pti\":[\"pti\"],\"image/vnd.adobe.photoshop\":[\"psd\"],\"image/vnd.airzip.accelerator.azv\":[\"azv\"],\"image/vnd.dece.graphic\":[\"uvi\",\"uvvi\",\"uvg\",\"uvvg\"],\"image/vnd.djvu\":[\"djvu\",\"djv\"],\"image/vnd.dvb.subtitle\":[\"*sub\"],\"image/vnd.dwg\":[\"dwg\"],\"image/vnd.dxf\":[\"dxf\"],\"image/vnd.fastbidsheet\":[\"fbs\"],\"image/vnd.fpx\":[\"fpx\"],\"image/vnd.fst\":[\"fst\"],\"image/vnd.fujixerox.edmics-mmr\":[\"mmr\"],\"image/vnd.fujixerox.edmics-rlc\":[\"rlc\"],\"image/vnd.microsoft.icon\":[\"ico\"],\"image/vnd.ms-dds\":[\"dds\"],\"image/vnd.ms-modi\":[\"mdi\"],\"image/vnd.ms-photo\":[\"wdp\"],\"image/vnd.net-fpx\":[\"npx\"],\"image/vnd.pco.b16\":[\"b16\"],\"image/vnd.tencent.tap\":[\"tap\"],\"image/vnd.valve.source.texture\":[\"vtf\"],\"image/vnd.wap.wbmp\":[\"wbmp\"],\"image/vnd.xiff\":[\"xif\"],\"image/vnd.zbrush.pcx\":[\"pcx\"],\"image/x-3ds\":[\"3ds\"],\"image/x-cmu-raster\":[\"ras\"],\"image/x-cmx\":[\"cmx\"],\"image/x-freehand\":[\"fh\",\"fhc\",\"fh4\",\"fh5\",\"fh7\"],\"image/x-icon\":[\"*ico\"],\"image/x-jng\":[\"jng\"],\"image/x-mrsid-image\":[\"sid\"],\"image/x-ms-bmp\":[\"*bmp\"],\"image/x-pcx\":[\"*pcx\"],\"image/x-pict\":[\"pic\",\"pct\"],\"image/x-portable-anymap\":[\"pnm\"],\"image/x-portable-bitmap\":[\"pbm\"],\"image/x-portable-graymap\":[\"pgm\"],\"image/x-portable-pixmap\":[\"ppm\"],\"image/x-rgb\":[\"rgb\"],\"image/x-tga\":[\"tga\"],\"image/x-xbitmap\":[\"xbm\"],\"image/x-xpixmap\":[\"xpm\"],\"image/x-xwindowdump\":[\"xwd\"],\"message/vnd.wfa.wsc\":[\"wsc\"],\"model/vnd.collada+xml\":[\"dae\"],\"model/vnd.dwf\":[\"dwf\"],\"model/vnd.gdl\":[\"gdl\"],\"model/vnd.gtw\":[\"gtw\"],\"model/vnd.mts\":[\"mts\"],\"model/vnd.opengex\":[\"ogex\"],\"model/vnd.parasolid.transmit.binary\":[\"x_b\"],\"model/vnd.parasolid.transmit.text\":[\"x_t\"],\"model/vnd.sap.vds\":[\"vds\"],\"model/vnd.usdz+zip\":[\"usdz\"],\"model/vnd.valve.source.compiled-map\":[\"bsp\"],\"model/vnd.vtu\":[\"vtu\"],\"text/prs.lines.tag\":[\"dsc\"],\"text/vnd.curl\":[\"curl\"],\"text/vnd.curl.dcurl\":[\"dcurl\"],\"text/vnd.curl.mcurl\":[\"mcurl\"],\"text/vnd.curl.scurl\":[\"scurl\"],\"text/vnd.dvb.subtitle\":[\"sub\"],\"text/vnd.fly\":[\"fly\"],\"text/vnd.fmi.flexstor\":[\"flx\"],\"text/vnd.graphviz\":[\"gv\"],\"text/vnd.in3d.3dml\":[\"3dml\"],\"text/vnd.in3d.spot\":[\"spot\"],\"text/vnd.sun.j2me.app-descriptor\":[\"jad\"],\"text/vnd.wap.wml\":[\"wml\"],\"text/vnd.wap.wmlscript\":[\"wmls\"],\"text/x-asm\":[\"s\",\"asm\"],\"text/x-c\":[\"c\",\"cc\",\"cxx\",\"cpp\",\"h\",\"hh\",\"dic\"],\"text/x-component\":[\"htc\"],\"text/x-fortran\":[\"f\",\"for\",\"f77\",\"f90\"],\"text/x-handlebars-template\":[\"hbs\"],\"text/x-java-source\":[\"java\"],\"text/x-lua\":[\"lua\"],\"text/x-markdown\":[\"mkd\"],\"text/x-nfo\":[\"nfo\"],\"text/x-opml\":[\"opml\"],\"text/x-org\":[\"*org\"],\"text/x-pascal\":[\"p\",\"pas\"],\"text/x-processing\":[\"pde\"],\"text/x-sass\":[\"sass\"],\"text/x-scss\":[\"scss\"],\"text/x-setext\":[\"etx\"],\"text/x-sfv\":[\"sfv\"],\"text/x-suse-ymp\":[\"ymp\"],\"text/x-uuencode\":[\"uu\"],\"text/x-vcalendar\":[\"vcs\"],\"text/x-vcard\":[\"vcf\"],\"video/vnd.dece.hd\":[\"uvh\",\"uvvh\"],\"video/vnd.dece.mobile\":[\"uvm\",\"uvvm\"],\"video/vnd.dece.pd\":[\"uvp\",\"uvvp\"],\"video/vnd.dece.sd\":[\"uvs\",\"uvvs\"],\"video/vnd.dece.video\":[\"uvv\",\"uvvv\"],\"video/vnd.dvb.file\":[\"dvb\"],\"video/vnd.fvt\":[\"fvt\"],\"video/vnd.mpegurl\":[\"mxu\",\"m4u\"],\"video/vnd.ms-playready.media.pyv\":[\"pyv\"],\"video/vnd.uvvu.mp4\":[\"uvu\",\"uvvu\"],\"video/vnd.vivo\":[\"viv\"],\"video/x-f4v\":[\"f4v\"],\"video/x-fli\":[\"fli\"],\"video/x-flv\":[\"flv\"],\"video/x-m4v\":[\"m4v\"],\"video/x-matroska\":[\"mkv\",\"mk3d\",\"mks\"],\"video/x-mng\":[\"mng\"],\"video/x-ms-asf\":[\"asf\",\"asx\"],\"video/x-ms-vob\":[\"vob\"],\"video/x-ms-wm\":[\"wm\"],\"video/x-ms-wmv\":[\"wmv\"],\"video/x-ms-wmx\":[\"wmx\"],\"video/x-ms-wvx\":[\"wvx\"],\"video/x-msvideo\":[\"avi\"],\"video/x-sgi-movie\":[\"movie\"],\"video/x-smv\":[\"smv\"],\"x-conference/x-cooltalk\":[\"ice\"]};","module.exports = {\"application/andrew-inset\":[\"ez\"],\"application/applixware\":[\"aw\"],\"application/atom+xml\":[\"atom\"],\"application/atomcat+xml\":[\"atomcat\"],\"application/atomdeleted+xml\":[\"atomdeleted\"],\"application/atomsvc+xml\":[\"atomsvc\"],\"application/atsc-dwd+xml\":[\"dwd\"],\"application/atsc-held+xml\":[\"held\"],\"application/atsc-rsat+xml\":[\"rsat\"],\"application/bdoc\":[\"bdoc\"],\"application/calendar+xml\":[\"xcs\"],\"application/ccxml+xml\":[\"ccxml\"],\"application/cdfx+xml\":[\"cdfx\"],\"application/cdmi-capability\":[\"cdmia\"],\"application/cdmi-container\":[\"cdmic\"],\"application/cdmi-domain\":[\"cdmid\"],\"application/cdmi-object\":[\"cdmio\"],\"application/cdmi-queue\":[\"cdmiq\"],\"application/cu-seeme\":[\"cu\"],\"application/dash+xml\":[\"mpd\"],\"application/davmount+xml\":[\"davmount\"],\"application/docbook+xml\":[\"dbk\"],\"application/dssc+der\":[\"dssc\"],\"application/dssc+xml\":[\"xdssc\"],\"application/ecmascript\":[\"es\",\"ecma\"],\"application/emma+xml\":[\"emma\"],\"application/emotionml+xml\":[\"emotionml\"],\"application/epub+zip\":[\"epub\"],\"application/exi\":[\"exi\"],\"application/express\":[\"exp\"],\"application/fdt+xml\":[\"fdt\"],\"application/font-tdpfr\":[\"pfr\"],\"application/geo+json\":[\"geojson\"],\"application/gml+xml\":[\"gml\"],\"application/gpx+xml\":[\"gpx\"],\"application/gxf\":[\"gxf\"],\"application/gzip\":[\"gz\"],\"application/hjson\":[\"hjson\"],\"application/hyperstudio\":[\"stk\"],\"application/inkml+xml\":[\"ink\",\"inkml\"],\"application/ipfix\":[\"ipfix\"],\"application/its+xml\":[\"its\"],\"application/java-archive\":[\"jar\",\"war\",\"ear\"],\"application/java-serialized-object\":[\"ser\"],\"application/java-vm\":[\"class\"],\"application/javascript\":[\"js\",\"mjs\"],\"application/json\":[\"json\",\"map\"],\"application/json5\":[\"json5\"],\"application/jsonml+json\":[\"jsonml\"],\"application/ld+json\":[\"jsonld\"],\"application/lgr+xml\":[\"lgr\"],\"application/lost+xml\":[\"lostxml\"],\"application/mac-binhex40\":[\"hqx\"],\"application/mac-compactpro\":[\"cpt\"],\"application/mads+xml\":[\"mads\"],\"application/manifest+json\":[\"webmanifest\"],\"application/marc\":[\"mrc\"],\"application/marcxml+xml\":[\"mrcx\"],\"application/mathematica\":[\"ma\",\"nb\",\"mb\"],\"application/mathml+xml\":[\"mathml\"],\"application/mbox\":[\"mbox\"],\"application/mediaservercontrol+xml\":[\"mscml\"],\"application/metalink+xml\":[\"metalink\"],\"application/metalink4+xml\":[\"meta4\"],\"application/mets+xml\":[\"mets\"],\"application/mmt-aei+xml\":[\"maei\"],\"application/mmt-usd+xml\":[\"musd\"],\"application/mods+xml\":[\"mods\"],\"application/mp21\":[\"m21\",\"mp21\"],\"application/mp4\":[\"mp4s\",\"m4p\"],\"application/msword\":[\"doc\",\"dot\"],\"application/mxf\":[\"mxf\"],\"application/n-quads\":[\"nq\"],\"application/n-triples\":[\"nt\"],\"application/node\":[\"cjs\"],\"application/octet-stream\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"],\"application/oda\":[\"oda\"],\"application/oebps-package+xml\":[\"opf\"],\"application/ogg\":[\"ogx\"],\"application/omdoc+xml\":[\"omdoc\"],\"application/onenote\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"],\"application/oxps\":[\"oxps\"],\"application/p2p-overlay+xml\":[\"relo\"],\"application/patch-ops-error+xml\":[\"xer\"],\"application/pdf\":[\"pdf\"],\"application/pgp-encrypted\":[\"pgp\"],\"application/pgp-signature\":[\"asc\",\"sig\"],\"application/pics-rules\":[\"prf\"],\"application/pkcs10\":[\"p10\"],\"application/pkcs7-mime\":[\"p7m\",\"p7c\"],\"application/pkcs7-signature\":[\"p7s\"],\"application/pkcs8\":[\"p8\"],\"application/pkix-attr-cert\":[\"ac\"],\"application/pkix-cert\":[\"cer\"],\"application/pkix-crl\":[\"crl\"],\"application/pkix-pkipath\":[\"pkipath\"],\"application/pkixcmp\":[\"pki\"],\"application/pls+xml\":[\"pls\"],\"application/postscript\":[\"ai\",\"eps\",\"ps\"],\"application/provenance+xml\":[\"provx\"],\"application/pskc+xml\":[\"pskcxml\"],\"application/raml+yaml\":[\"raml\"],\"application/rdf+xml\":[\"rdf\",\"owl\"],\"application/reginfo+xml\":[\"rif\"],\"application/relax-ng-compact-syntax\":[\"rnc\"],\"application/resource-lists+xml\":[\"rl\"],\"application/resource-lists-diff+xml\":[\"rld\"],\"application/rls-services+xml\":[\"rs\"],\"application/route-apd+xml\":[\"rapd\"],\"application/route-s-tsid+xml\":[\"sls\"],\"application/route-usd+xml\":[\"rusd\"],\"application/rpki-ghostbusters\":[\"gbr\"],\"application/rpki-manifest\":[\"mft\"],\"application/rpki-roa\":[\"roa\"],\"application/rsd+xml\":[\"rsd\"],\"application/rss+xml\":[\"rss\"],\"application/rtf\":[\"rtf\"],\"application/sbml+xml\":[\"sbml\"],\"application/scvp-cv-request\":[\"scq\"],\"application/scvp-cv-response\":[\"scs\"],\"application/scvp-vp-request\":[\"spq\"],\"application/scvp-vp-response\":[\"spp\"],\"application/sdp\":[\"sdp\"],\"application/senml+xml\":[\"senmlx\"],\"application/sensml+xml\":[\"sensmlx\"],\"application/set-payment-initiation\":[\"setpay\"],\"application/set-registration-initiation\":[\"setreg\"],\"application/shf+xml\":[\"shf\"],\"application/sieve\":[\"siv\",\"sieve\"],\"application/smil+xml\":[\"smi\",\"smil\"],\"application/sparql-query\":[\"rq\"],\"application/sparql-results+xml\":[\"srx\"],\"application/srgs\":[\"gram\"],\"application/srgs+xml\":[\"grxml\"],\"application/sru+xml\":[\"sru\"],\"application/ssdl+xml\":[\"ssdl\"],\"application/ssml+xml\":[\"ssml\"],\"application/swid+xml\":[\"swidtag\"],\"application/tei+xml\":[\"tei\",\"teicorpus\"],\"application/thraud+xml\":[\"tfi\"],\"application/timestamped-data\":[\"tsd\"],\"application/toml\":[\"toml\"],\"application/trig\":[\"trig\"],\"application/ttml+xml\":[\"ttml\"],\"application/ubjson\":[\"ubj\"],\"application/urc-ressheet+xml\":[\"rsheet\"],\"application/urc-targetdesc+xml\":[\"td\"],\"application/voicexml+xml\":[\"vxml\"],\"application/wasm\":[\"wasm\"],\"application/widget\":[\"wgt\"],\"application/winhlp\":[\"hlp\"],\"application/wsdl+xml\":[\"wsdl\"],\"application/wspolicy+xml\":[\"wspolicy\"],\"application/xaml+xml\":[\"xaml\"],\"application/xcap-att+xml\":[\"xav\"],\"application/xcap-caps+xml\":[\"xca\"],\"application/xcap-diff+xml\":[\"xdf\"],\"application/xcap-el+xml\":[\"xel\"],\"application/xcap-ns+xml\":[\"xns\"],\"application/xenc+xml\":[\"xenc\"],\"application/xhtml+xml\":[\"xhtml\",\"xht\"],\"application/xliff+xml\":[\"xlf\"],\"application/xml\":[\"xml\",\"xsl\",\"xsd\",\"rng\"],\"application/xml-dtd\":[\"dtd\"],\"application/xop+xml\":[\"xop\"],\"application/xproc+xml\":[\"xpl\"],\"application/xslt+xml\":[\"*xsl\",\"xslt\"],\"application/xspf+xml\":[\"xspf\"],\"application/xv+xml\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"],\"application/yang\":[\"yang\"],\"application/yin+xml\":[\"yin\"],\"application/zip\":[\"zip\"],\"audio/3gpp\":[\"*3gpp\"],\"audio/adpcm\":[\"adp\"],\"audio/amr\":[\"amr\"],\"audio/basic\":[\"au\",\"snd\"],\"audio/midi\":[\"mid\",\"midi\",\"kar\",\"rmi\"],\"audio/mobile-xmf\":[\"mxmf\"],\"audio/mp3\":[\"*mp3\"],\"audio/mp4\":[\"m4a\",\"mp4a\"],\"audio/mpeg\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"],\"audio/ogg\":[\"oga\",\"ogg\",\"spx\",\"opus\"],\"audio/s3m\":[\"s3m\"],\"audio/silk\":[\"sil\"],\"audio/wav\":[\"wav\"],\"audio/wave\":[\"*wav\"],\"audio/webm\":[\"weba\"],\"audio/xm\":[\"xm\"],\"font/collection\":[\"ttc\"],\"font/otf\":[\"otf\"],\"font/ttf\":[\"ttf\"],\"font/woff\":[\"woff\"],\"font/woff2\":[\"woff2\"],\"image/aces\":[\"exr\"],\"image/apng\":[\"apng\"],\"image/avif\":[\"avif\"],\"image/bmp\":[\"bmp\"],\"image/cgm\":[\"cgm\"],\"image/dicom-rle\":[\"drle\"],\"image/emf\":[\"emf\"],\"image/fits\":[\"fits\"],\"image/g3fax\":[\"g3\"],\"image/gif\":[\"gif\"],\"image/heic\":[\"heic\"],\"image/heic-sequence\":[\"heics\"],\"image/heif\":[\"heif\"],\"image/heif-sequence\":[\"heifs\"],\"image/hej2k\":[\"hej2\"],\"image/hsj2\":[\"hsj2\"],\"image/ief\":[\"ief\"],\"image/jls\":[\"jls\"],\"image/jp2\":[\"jp2\",\"jpg2\"],\"image/jpeg\":[\"jpeg\",\"jpg\",\"jpe\"],\"image/jph\":[\"jph\"],\"image/jphc\":[\"jhc\"],\"image/jpm\":[\"jpm\"],\"image/jpx\":[\"jpx\",\"jpf\"],\"image/jxr\":[\"jxr\"],\"image/jxra\":[\"jxra\"],\"image/jxrs\":[\"jxrs\"],\"image/jxs\":[\"jxs\"],\"image/jxsc\":[\"jxsc\"],\"image/jxsi\":[\"jxsi\"],\"image/jxss\":[\"jxss\"],\"image/ktx\":[\"ktx\"],\"image/ktx2\":[\"ktx2\"],\"image/png\":[\"png\"],\"image/sgi\":[\"sgi\"],\"image/svg+xml\":[\"svg\",\"svgz\"],\"image/t38\":[\"t38\"],\"image/tiff\":[\"tif\",\"tiff\"],\"image/tiff-fx\":[\"tfx\"],\"image/webp\":[\"webp\"],\"image/wmf\":[\"wmf\"],\"message/disposition-notification\":[\"disposition-notification\"],\"message/global\":[\"u8msg\"],\"message/global-delivery-status\":[\"u8dsn\"],\"message/global-disposition-notification\":[\"u8mdn\"],\"message/global-headers\":[\"u8hdr\"],\"message/rfc822\":[\"eml\",\"mime\"],\"model/3mf\":[\"3mf\"],\"model/gltf+json\":[\"gltf\"],\"model/gltf-binary\":[\"glb\"],\"model/iges\":[\"igs\",\"iges\"],\"model/mesh\":[\"msh\",\"mesh\",\"silo\"],\"model/mtl\":[\"mtl\"],\"model/obj\":[\"obj\"],\"model/step+xml\":[\"stpx\"],\"model/step+zip\":[\"stpz\"],\"model/step-xml+zip\":[\"stpxz\"],\"model/stl\":[\"stl\"],\"model/vrml\":[\"wrl\",\"vrml\"],\"model/x3d+binary\":[\"*x3db\",\"x3dbz\"],\"model/x3d+fastinfoset\":[\"x3db\"],\"model/x3d+vrml\":[\"*x3dv\",\"x3dvz\"],\"model/x3d+xml\":[\"x3d\",\"x3dz\"],\"model/x3d-vrml\":[\"x3dv\"],\"text/cache-manifest\":[\"appcache\",\"manifest\"],\"text/calendar\":[\"ics\",\"ifb\"],\"text/coffeescript\":[\"coffee\",\"litcoffee\"],\"text/css\":[\"css\"],\"text/csv\":[\"csv\"],\"text/html\":[\"html\",\"htm\",\"shtml\"],\"text/jade\":[\"jade\"],\"text/jsx\":[\"jsx\"],\"text/less\":[\"less\"],\"text/markdown\":[\"markdown\",\"md\"],\"text/mathml\":[\"mml\"],\"text/mdx\":[\"mdx\"],\"text/n3\":[\"n3\"],\"text/plain\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"],\"text/richtext\":[\"rtx\"],\"text/rtf\":[\"*rtf\"],\"text/sgml\":[\"sgml\",\"sgm\"],\"text/shex\":[\"shex\"],\"text/slim\":[\"slim\",\"slm\"],\"text/spdx\":[\"spdx\"],\"text/stylus\":[\"stylus\",\"styl\"],\"text/tab-separated-values\":[\"tsv\"],\"text/troff\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"],\"text/turtle\":[\"ttl\"],\"text/uri-list\":[\"uri\",\"uris\",\"urls\"],\"text/vcard\":[\"vcard\"],\"text/vtt\":[\"vtt\"],\"text/xml\":[\"*xml\"],\"text/yaml\":[\"yaml\",\"yml\"],\"video/3gpp\":[\"3gp\",\"3gpp\"],\"video/3gpp2\":[\"3g2\"],\"video/h261\":[\"h261\"],\"video/h263\":[\"h263\"],\"video/h264\":[\"h264\"],\"video/iso.segment\":[\"m4s\"],\"video/jpeg\":[\"jpgv\"],\"video/jpm\":[\"*jpm\",\"jpgm\"],\"video/mj2\":[\"mj2\",\"mjp2\"],\"video/mp2t\":[\"ts\"],\"video/mp4\":[\"mp4\",\"mp4v\",\"mpg4\"],\"video/mpeg\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"],\"video/ogg\":[\"ogv\"],\"video/quicktime\":[\"qt\",\"mov\"],\"video/webm\":[\"webm\"]};","// empty module for shims\nmodule.exports = {};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"thebe-lite:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t};\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","__webpack_require__.amdO = {};","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".thebe-lite.min.js\";\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t143: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkthebe_lite\"] = self[\"webpackChunkthebe_lite\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(1920);\n"],"names":["Object","defineProperty","exports","value","BaseManager","signaling_1","serverconnection_1","constructor","options","_a","this","_isDisposed","_disposed","Signal","serverSettings","ServerConnection","makeSettings","disposed","isDisposed","isActive","dispose","emit","undefined","clearData","BuildManager","coreutils_1","_url","baseUrl","appUrl","URLExt","join","isAvailable","PageConfig","getOption","toLowerCase","shouldCheck","getStatus","makeRequest","then","response","status","ResponseError","json","data","Error","message","build","method","cancel","ConfigWithDefaults","ConfigSection","__1","create","section","DefaultConfigSection","load","settings","encodeURIComponent","name","_data","async","newdata","init","body","JSON","stringify","_b","_className","_section","_defaults","defaults","className","get","key","_classData","set","d","d2","update","__createBinding","o","m","k","k2","desc","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","__setModuleDefault","v","__importStar","mod","result","prototype","hasOwnProperty","call","Drive","ContentsManager","Contents","validate","Private","validateContentsModel","contents","validateCheckpointModel","checkpoint","_additionalDrives","Map","_fileChanged","_defaultDrive","defaultDrive","fileChanged","connect","_onFileChanged","addDrive","drive","getSharedModelFactory","path","_driveForPath","sharedModelFactory","localPath","parts","split","firstParts","length","has","PathExt","slice","removeSlash","normalize","resolvePath","root","driveName","resolved","resolve","contentsModel","listing","type","content","item","push","_toGlobalPath","serverPath","getDownloadUrl","newUntitled","globalPath","delete","rename","newPath","drive1","path1","drive2","path2","save","copy","fromFile","toDir","createCheckpoint","listCheckpoints","restoreCheckpoint","checkpointID","deleteCheckpoint","sender","args","newValue","oldValue","_c","_apiEndpoint","apiEndpoint","url","_getUrl","params","objectToQueryString","encodeParts","xsrfTokenMatch","document","cookie","match","fullUrl","URL","searchParams","append","toString","Promise","ext","normalizeExtension","oldLocalPath","newLocalPath","copy_from","Array","isArray","i","map","extension","indexOf","validate_1","model","validateProperty","EventManager","polling_1","SERVICE_EVENTS_URL","_socket","_poll","Poll","factory","_subscribe","_stream","Stream","start","stream","socket","onopen","onerror","onmessage","onclose","close","stop","event","token","_","reject","WebSocket","wsUrl","msg","parse","__exportStar","p","CommHandler","disposable_1","KernelMessage","DisposableDelegate","target","id","kernel","disposeCb","super","_target","_id","_kernel","commId","targetName","onClose","_onClose","cb","onMsg","_onMsg","open","metadata","buffers","createMessage","msgType","channel","username","session","clientId","comm_id","target_name","sendShellMessage","send","disposeOnDone","future","KernelConnection","coreutils_2","comm_1","future_1","serialize_1","kernelspec_1","restapi","RESTARTING_KERNEL_SESSION","_d","_createSocket","useProtocols","_errorIfDisposed","_clearSocket","_updateConnectionStatus","partialUrl","KERNEL_SERVICE_URL","display","replace","console","debug","_clientId","appendToken","supportedProtocols","_supportedProtocols","_ws","binaryType","alreadyCalledOnclose","getKernelModel","evt","_reason","_model","execution_state","_updateStatus","_onWSClose","err","NetworkError","timeout","getRandomIntInclusive","setTimeout","earlyClose","_onWSMessage","_onWSOpen","protocol","includes","log","_selectedProtocol","deserialize","validateMessage","error","_kernelSession","header","_msgChain","_handleMessage","catch","startsWith","_anyMessage","direction","_reconnect","_name","_status","_connectionStatus","_username","_reconnectLimit","_reconnectAttempt","_reconnectTimeout","values","supportedKernelWebSocketProtocols","_futures","_comms","_targetRegistry","_info","PromiseDelegate","_pendingMessages","_statusChanged","_connectionStatusChanged","_iopubMessage","_pendingInput","_unhandledMessage","_displayIdToParentIds","_msgIdToDisplayIds","_hasPendingInput","_noOp","UUID","uuid4","handleComms","statusChanged","connectionStatusChanged","iopubMessage","unhandledMessage","reason","anyMessage","pendingInput","connectionStatus","info","promise","spec","_specPromise","KernelSpecAPI","getSpecs","specs","kernelspecs","clone","_clearKernelState","expectReply","_sendKernelShellControl","KernelShellFutureHandler","sendControlMessage","KernelControlFutureHandler","ctor","_sendMessage","msgId","msg_id","displayIds","forEach","displayId","msgIds","idx","splice","queue","isInfoRequestMsg","serialize","hasPendingInput","interruptKernel","restartKernel","reconnect","fulfill","disconnect","shutdownKernel","handleShutdown","reply","handleShellMessage","e","requestComplete","requestInspect","requestHistory","requestExecute","silent","store_history","user_expressions","allow_stdin","stop_on_error","requestDebug","requestIsComplete","requestCommInfo","sendInputReply","parent_header","createComm","comm","_unregisterComm","hasComm","registerCommTarget","callback","removeCommTarget","registerMessageHook","hook","removeMessageHook","removeInputGuard","parentIds","updateMsg","JSONExt","deepCopy","msg_type","all","parentId","handleMsg","logKernelStatus","_sendPending","shift","clear","_assertCurrentMessage","loadObject","target_module","clearTimeout","restarting","requestKernelInfo","sendPendingCalled","sendPendingOnce","timeoutHandle","handled","isDisplayDataMsg","isUpdateDisplayDataMsg","isExecuteResultMsg","transient","_handleDisplayId","parentHeader","owned","executionState","_handleCommOpen","_handleCommMsg","_handleCommClose","Math","pow","warn","floor","done","moduleName","registry","requirejs","min","max","ceil","random","KernelFutureHandler","_stdin","noOp","_iopub","_reply","_done","_hooks","HookList","_disposeOnDone","_msg","_setFlag","KernelFutureFlag","GotReply","onReply","onIOPub","onStdin","add","remove","_testFlag","IsDone","_handleReply","_handleStdin","_handleIOPub","_replyMsg","GotIdle","_handleDone","stdin","process","iopub","isStatusMsg","flag","defer","requestAnimationFrame","setImmediate","index","_scheduleCompact","_processing","processing","continueHandling","_compactScheduled","_compact","numNulls","len","KernelAPI","Kernel","default_1","KernelManager","basemanager_1","restapi_1","_isReady","_kernelConnections","Set","_models","_runningChanged","_connectionFailure","_pollModels","auto","requestRunning","frequency","interval","backoff","standby","_ready","tick","isReady","ready","runningChanged","connectionFailure","x","connectTo","kc","kernelConnection","_onStarted","refreshRunning","running","refresh","createOptions","connectOptions","startNew","keys","models","listRunning","size","every","existing","connections","last_activity","traceback","_onStatusChanged","_onDisposed","NoopManager","arguments","_readyPromise","parentReady","isInputReplyMsg","isInputRequestMsg","isDebugReplyMsg","isDebugRequestMsg","isExecuteReplyMsg","isCommMsgMsg","isCommCloseMsg","isCommOpenMsg","isDebugEventMsg","isClearOutputMsg","isErrorMsg","isExecuteInputMsg","isStreamMsg","_e","date","Date","toISOString","version","validateModels","validateModel","v1KernelWebsocketJupyterOrg","serializeV1KernelWebsocketJupyterOrg","serializeDefault","deserializeV1KernelWebsocketJupyterOrg","deserializeDefault","binMsg","DataView","offsetNumber","Number","getBigUint64","offsets","decoder","TextDecoder","decode","encoder","TextEncoder","channelEncoded","encode","headerEncoded","parentHeaderEncoded","metadataEncoded","contentEncoded","binMsgNoBuff","Uint8Array","buffersByteLength","buffer","byteLength","word","ArrayBuffer","setBigUint64","BigInt","isView","buf","nbufs","getUint32","jsonBytes","deserializeBinary","origBuffers","jsonUtf8","b","msgBuf","view","setUint32","serializeBinary","HEADER_FIELDS","IOPUB_CONTENT_FIELDS","text","display_data","execute_input","code","execution_count","execute_result","ename","evalue","clear_output","wait","comm_open","comm_msg","comm_close","shutdown_reply","restart","validateHeader","fields","names","validateIOPubContent","KernelSpec","KernelSpecManager","_specs","_specsChanged","requestSpecs","_pollSpecs","specsChanged","deepEqual","validateSpecModels","validateSpecModel","env","resources","language","display_name","argv","defaultSpec","default","ks","ServiceManager","builder_1","contents_1","event_1","kernel_1","nbconvert_1","session_1","setting_1","terminal_1","user_1","workspace_1","normalized","events","kernels","sessions","SessionManager","kernelManager","SettingManager","terminals","TerminalManager","builder","workspaces","WorkspaceManager","nbconvert","NbConvertManager","user","UserManager","_onConnectionFailure","readyList","_exportFormats","_requestingFormats","base","exportList","mimeType","output_mimetype","force","fetchExportFormats","WEBSOCKET","window","handleRequest","static","_defaultMessage","statusText","TypeError","original","stack","pageBaseUrl","getBaseUrl","pageWsUrl","getWsUrl","cache","credentials","fetch","Headers","Request","getToken","JEST_WORKER_ID","getHostName","test","getTime","request","authenticated","headers","xsrfToken","matches","getCookie","SessionConnection","_path","_type","_kernelChanged","_propertyChanged","_connectToKernel","connectToKernel","_kernelConnectionOptions","kernelConnectionOptions","setupKernel","kernelChanged","propertyChanged","oldModel","_handleModelChange","_patch","shutdownSession","onKernelStatus","onKernelConnectionStatus","onPendingInput","onUnhandledMessage","onIOPubMessage","onAnyMessage","state","updateSession","SessionAPI","Session","_sessionConnections","_kernelManager","sessionConnection","startSession","filter","shutdown","sc","_onChanged","getSessionModel","getSessionUrl","SESSION_SERVICE_URL","updateLegacySessionModel","validate_2","notebook","statedb_1","DataConnector","query","ids","plugin","composite","raw","idsOnly","idsOnlyParam","ids_only","TerminalConnection","_messageReceived","messageReceived","shutdownTerminal","getTermUrl","TERMINAL_SERVICE_URL","TerminalAPI","Terminal","_names","_terminalConnections","terminalConnection","Symbol","iterator","cwd","sort","tc","String","errorIfNotAvailable","SERVICE_ID","_userChanged","requestUser","identity","_identity","permissions","_permissions","userChanged","oldUser","newUser","localStorage","getItem","initials","color","localUser","substring","getRandomColor","setItem","userColors","object","typeName","valid","findIndex","workspace","ActivityMonitor","_timer","_timeout","_activityStopped","signal","_onSignalFired","activityStopped","_sender","_args","MarkdownCodeBlocks","CODE_BLOCK_MARKER","markdownExtensions","MarkdownCodeBlock","startLine","endLine","isMarkdown","findMarkdownCodeBlocks","lines","codeBlocks","currentBlock","lineIndex","line","lineContainsMarker","constructingBlock","firstIndex","lastIndex","lastIndexOf","__importDefault","minimist_1","url_1","configData","getBodyData","found","el","getElementById","textContent","cli","fullPath","eval","isObject","setOption","last","getTreeUrl","getShareUrl","getTreeShareUrl","getUrl","toShare","mode","labOrDoc","defaultWorkspace","treePath","getNBConvertURL","format","download","notebookPath","getNotebookVersion","notebookVersion","Extension","val","dataset","decodeURIComponent","populate","deferred","disabled","isDeferred","separatorIndex","extName","some","isDisabled","path_1","paths","posix","basename","dirname","dir","extname","relative","from","to","signalToPromise","waitForSignal","cleanup","slot","Text","HAS_SURROGATES","jsIndexToCharIndex","jsIdx","charIdx","charCode","charCodeAt","nextCharCode","charIndexToJsIndex","camelCase","str","upper","p1","p2","toUpperCase","titleCase","charAt","Time","UNITS","milliseconds","formatHuman","lang","documentElement","formatter","Intl","RelativeTimeFormat","numeric","delta","now","unit","amount","DateTimeFormat","dateStyle","timeStyle","url_parse_1","a","createElement","href","u","isSchemaLess","slashes","prefix","auth","host","pathname","hostname","queryStringToObject","reduce","acc","isLocal","RestorablePool","properties_1","_added","_current","_currentChanged","_hasRestored","_objects","_restore","_restored","_updated","namespace","added","current","obj","currentChanged","restored","updated","warning","_onInstanceDisposed","injectedProperty","connector","objName","nameProperty","find","fn","filtered","inject","command","when","promises","list","concat","saved","execute","injected","oldName","newName","AttachedProperty","StateDB","_changed","transform","_connector","Connector","transformation","_clear","_merge","_overwrite","changed","_fetch","_list","_remove","_save","_storage","IStateDB","Token","isPrimitive","first","second","a1","a2","n","deepArrayEqual","firstValue","secondValue","deepObjectEqual","deepArrayCopy","subvalue","deepObjectCopy","emptyObject","freeze","emptyArray","fallbackRandomValues","Random","getRandomValues","crypto","msCrypto","bytes","lut","uuid4Factory","MimeData","_types","_values","types","hasData","mime","getData","setData","_resolve","_reject","description","_tokenStructuralPropertyT","_fn","ObservableDisposableDelegate","DisposableSet","_items","contains","items","ObservableDisposableSet","_lingered","_tick","_ticked","_factory","_linger","linger","DEFAULT_LINGER","_standby","DEFAULT_STANDBY","_state","DEFAULT_STATE","timestamp","DEFAULT_FREQUENCY","DEFAULT_NAME","_frequency","round","NEVER","MAX_INTERVAL","phase","ticked","asyncIterator","DISPOSED_STATE","schedule","IMMEDIATE","next","pending","scheduled","payload","_execute","hidden","rejected","sleep","Infinity","DEFAULT_BACKOFF","growth","addEventListener","visibilityState","RateLimiter","limit","poll","Debouncer","invoke","Throttler","_trailing","edge","_interval","idle","_pid","nextPID","_create","_coerce","coerce","_compare","compare","owner","ensureMap","_createValue","_coerceValue","_maybeNotify","_compareValue","ownerData","WeakMap","ArrayExt","StringExt","firstIndexOf","array","span","j","findFirstIndex","findLastIndex","reverse","removeAt","findFirstValue","findLastValue","lowerBound","begin","half","middle","upperBound","shallowEqual","step","move","fromIndex","toIndex","rotate","pivot","fill","insert","removeFirstOf","removeLastOf","removeAllOf","count","removeFirstWhere","removeLastWhere","removeAllWhere","rangeLength","findIndices","source","indices","matchSumOfSquares","score","matchSumOfDeltas","highlight","cmp","thisArg","disconnectBetween","receiver","disconnectSender","disconnectReceiver","disconnectAll","getExceptionHandler","exceptionHandler","setExceptionHandler","handler","old","_pending","receivers","receiversForSender","connection","scheduleCleanup","sendersForReceiver","senders","findConnection","invokeSlot","dirtySet","cleanupDirtySet","cleanupConnections","isDeadConnection","module","createCommonjsModule","_global","global","self","Function","__g","_core","core","__e","_isObject","it","_anObject","_fails","exec","_descriptors","is","_ie8DomDefine","dP","_objectDp","f","O","P","Attributes","S","valueOf","_toPrimitive","_hide","bitmap","_propertyDesc","_has","px","_shared","SHARED","store","copyright","_functionToString","_redefine","SRC","_uid","TO_STRING","TPL","inspectSource","safe","isFunction","_ctx","that","_aFunction","c","apply","PROTOTYPE","$export","own","out","exp","IS_FORCED","F","IS_GLOBAL","G","IS_STATIC","IS_PROTO","IS_BIND","B","expProto","U","W","R","_export","_toInteger","isNaN","$at","pos","s","_defined","l","codePointAt","fromCharCode","$fromCodePoint","fromCodePoint","arguments$1","res","aLen","RangeError","parseState","column","lexState","doubleQuote","sign","unicode","Space_Separator","ID_Start","ID_Continue","util","isSpaceSeparator","isIdStartChar","isIdContinueChar","isDigit","isHexDigit","internalize","holder","reviver","replacement","key$1","replacement$1","lex","peek","lexStates","read","newToken","comment","invalidChar","multiLineComment","multiLineCommentAsterisk","singleLineComment","literal","NaN","identifierNameStartEscape","unicodeEscape","invalidIdentifier","identifierName","identifierNameEscape","zero","decimalInteger","decimalPointLeading","decimalPoint","decimalFraction","decimalExponent","decimalExponentSign","decimalExponentInteger","hexadecimal","hexadecimalInteger","string","parseInt","hexEscape","escape","formatChar","separatorChar","beforePropertyName","afterPropertyName","beforePropertyValue","afterPropertyValue","beforeArrayValue","afterArrayValue","end","parseStates","invalidEOF","pop","parent","syntaxError","replacements","hexString","SyntaxError","lineNumber","columnNumber","replacer","space","propertyList","replacerFunc","quote","indent","gap","substr","serializeProperty","toJSON5","toJSON","Boolean","quoteString","stepback","final","partial","propertyString","separator","properties$1","serializeArray","properties","member","serializeKey","serializeObject","quotes","product","quoteChar","RegExp","firstChar","getSerializerPromise","localForageInstance","getSerializer","executeCallback","storageRepository","_driver","_initStorage","dbInfo","database","table","storeName","db","_dbInfo","serializer","iterate","iterationNumber","originalValue","serializeAsync","removeItem","t","r","_dereq_","scheduleDrain","draining","Mutation","MutationObserver","WebKitMutationObserver","called","observer","nextTick","element","createTextNode","observe","characterData","MessageChannel","scriptEl","onreadystatechange","parentNode","removeChild","appendChild","port1","port2","postMessage","oldQueue","task","g","immediate","INTERNAL","handlers","REJECTED","FULFILLED","PENDING","resolver","outcome","safelyResolveThenable","QueueItem","onFulfilled","onRejected","callFulfilled","otherCallFulfilled","callRejected","otherCallRejected","unwrap","func","returnValue","getThen","thenable","onError","onSuccess","tryCatch","iterable","allResolver","outValue","race","_typeof","idb","indexedDB","webkitIndexedDB","mozIndexedDB","OIndexedDB","msIndexedDB","getIDB","createBlob","Blob","BlobBuilder","MSBlobBuilder","MozBlobBuilder","WebKitBlobBuilder","getBlob","Promise$1","executeTwoCallbacks","errorCallback","normalizeKey","getCallback","DETECT_BLOB_SUPPORT_STORE","supportsBlobs","dbContexts","READ_ONLY","READ_WRITE","_binStringToArrayBuffer","bin","arr","_checkBlobSupport","txn","transaction","blob","objectStore","put","onabort","preventDefault","stopPropagation","oncomplete","matchedChrome","navigator","userAgent","matchedEdge","_checkBlobSupportWithoutCaching","_deferReadiness","dbContext","deferredOperation","deferredOperations","dbReady","_advanceReadiness","_rejectReadiness","_getConnection","upgradeNeeded","forages","dbArgs","openreq","onupgradeneeded","createObjectStore","oldVersion","ex","newVersion","onsuccess","onversionchange","_getOriginalConnection","_getUpgradedConnection","_isUpgradeNeeded","defaultVersion","isNewStore","objectStoreNames","isDowngrade","isUpgrade","incVersion","_decodeBlob","encodedBlob","atob","_isEncodedBlob","__local_forage_encoded_blob","_fullyReady","_initReady","createTransaction","retries","tx","forage","_tryReconnect","asyncStorage","initPromises","ignoreErrors","_defaultConfig","_support","isSafari","openDatabase","platform","hasFetch","IDBKeyRange","isIndexedDBValid","req","openCursor","cursor","blobSupport","reader","FileReader","onloadend","base64","btoa","readAsBinaryString","advanced","openKeyCursor","advance","dropInstance","currentConfig","config","dbPromise","dropObjectPromise","deleteObjectStore","_forage2","dropDBPromise","deleteDatabase","onblocked","BASE_CHARS","BLOB_TYPE_PREFIX","BLOB_TYPE_PREFIX_REGEX","SERIALIZED_MARKER","SERIALIZED_MARKER_LENGTH","TYPE_ARRAYBUFFER","TYPE_BLOB","TYPE_INT8ARRAY","TYPE_UINT8ARRAY","TYPE_UINT8CLAMPEDARRAY","TYPE_INT16ARRAY","TYPE_INT32ARRAY","TYPE_UINT16ARRAY","TYPE_UINT32ARRAY","TYPE_FLOAT32ARRAY","TYPE_FLOAT64ARRAY","TYPE_SERIALIZED_MARKER_LENGTH","toString$1","stringToBuffer","serializedString","encoded1","encoded2","encoded3","encoded4","bufferLength","bufferToString","base64String","localforageSerializer","valueType","marker","fileReader","onload","readAsArrayBuffer","blobType","matcher","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","createDbTable","executeSql","tryExecuteSql","sqlStatement","SYNTAX_ERR","results","rows","_setItem","retriesLeft","sqlError","QUOTA_ERR","webSQLStorage","dbInfoPromise","storeNames","getAllStoreNames","operationInfo","dropTable","operations","_getKeyPrefix","defaultConfig","keyPrefix","_isLocalStorageUsable","localStorageTestKey","checkIfLocalStorageThrows","localStorageWrapper","isLocalStorageValid","keyPrefixLength","itemKey","searchElement","y","arg","DefinedDrivers","DriverSupport","DefaultDrivers","INDEXEDDB","WEBSQL","LOCALSTORAGE","DefaultDriverOrder","OptionalDriverMethods","LibraryMethods","DefaultConfig","driver","callWhenReady","libraryMethod","extend","_key","LocalForage","driverTypeKey","instance","Constructor","_classCallCheck","driverName","defineDriver","_config","_driverSet","_initDriver","_wrapLibraryMethodsWithReady","setDriver","driverObject","complianceError","driverMethods","driverMethodName","methodNotImplementedFactory","methodName","_i","_len","optionalDriverMethod","configureMissingMethods","setDriverSupport","support","getDriver","getDriverPromise","serializerPromise","drivers","supportedDrivers","_getSupportedDrivers","setDriverToConfig","extendSelfWithDriver","_extend","oldDriverSetDone","currentDriverIndex","driverPromiseLoop","initDriver","supports","libraryMethodsAndProperties","createInstance","localforage_js","isNumber","isConstructorOrProto","opts","flags","bools","strings","unknownFn","unknown","boolean","allBools","aliases","aliasIsBoolean","alias","setKey","lastKey","setArg","argDefined","notFlags","letters","broken","stopEarly","commonjsGlobal","requiresPort","port","input","querystringify_1","pairs","part","parser","CRHTLF","protocolre","windowsDriveLetter","whitespace","trimLeft","rules","address","isSpecial","ignore","hash","lolcation","loc","location","finaldestination","Url","unescape","scheme","extractProtocol","rest","forwardSlashes","otherSlashes","slashesCount","extracted","instruction","instructions","unshift","up","password","origin","char","ins","qs","urlParse","delay","context","timeoutContext","itemInArray","EventTarget","listeners","trimQueryPartFromURL","queryIndex","listener","removeEventListener","removingListener","arrayOfListeners","dispatchEvent","this$1","customArguments","eventName","NetworkBridge","urlMap","attachWebSocket","websocket","serverURL","connectionLookup","server","websockets","addMembershipToRoom","room","roomMemberships","attachServer","serverUrl","serverLookup","websocketsLookup","broadcaster","removeServer","removeWebSocket","removeMembershipFromRoom","memberships","networkBridge","CLOSE_CODES","CLOSE_NORMAL","CLOSE_GOING_AWAY","CLOSE_PROTOCOL_ERROR","CLOSE_UNSUPPORTED","CLOSE_NO_STATUS","CLOSE_ABNORMAL","UNSUPPORTED_DATA","POLICY_VIOLATION","CLOSE_TOO_LARGE","MISSING_EXTENSION","INTERNAL_ERROR","SERVICE_RESTART","TRY_AGAIN_LATER","TLS_HANDSHAKE","ERROR_PREFIX","CONSTRUCTOR_ERROR","CLOSE_ERROR","EVENT","CONSTRUCT","MESSAGE","CLOSE","EventPrototype","stopImmediatePropagation","initEvent","bubbles","cancelable","Event","EventPrototype$$1","eventInitConfig","timeStamp","srcElement","isTrusted","eventPhase","defaultPrevented","currentTarget","cancelBubble","__proto__","MessageEvent","lastEventId","ports","canncelBubble","CloseEvent","wasClean","createEvent","eventObject","createMessageEvent","messageEvent","createCloseEvent","closeEvent","closeWebSocketConnection","readyState","WebSocket$1","CLOSING","CLOSED","normalizeSendData","proxies","proxyFactory","proxy","Proxy","prop","toSocketName","EventTarget$$1","protocols","_onopen","_onmessage","_onerror","_onclose","urlRecord","urlVerification","uniq","duplicates","protocolVerification","CONNECTING","client","verifyClient","selectProtocol","selectedProtocol","isFilled","isRequested","OPEN","prototypeAccessors","errorEvent","failWebSocketConnection","defineProperties","SocketIO$1","SocketIO","broadcast","in","on","off","hasListeners","leave","IO","retrieveGlobalObject","defaultOptions","mock","Server$1","Server","originalWebSocket","assign","mockWebsocket","globalObj","restoreWebsocket","normalizedData","messageData","clients","broadcastList","deduped","chainedRoom","chainedBroadcaster","simulate","of","SocketIO$$1","assertPath","normalizeStringPosix","allowAboveRoot","lastSegmentLength","lastSlash","dots","lastSlashIndex","resolvedPath","resolvedAbsolute","isAbsolute","trailingSeparator","joined","fromStart","fromEnd","fromLen","toStart","toLen","lastCommonSep","fromCode","_makeLong","hasRoot","matchedSlash","extIdx","firstNonSlashEnd","startDot","startPart","preDotState","pathObject","sep","_format","ret","delimiter","win32","setupThebeLite","thebeLite","startJupyterLiteServer","serverExtensions","activePlugins","plugins","litePluginSettings","litePluginsToRegister","liteExtensionPromises","liteExtension","scope","_JUPYTERLAB","createModule","allSettled","jupyterLiteServer","JupyterLiteServer","registerPluginModules","serviceManager","extendStatics","setPrototypeOf","__extends","__","__assign","__rest","getOwnPropertySymbols","propertyIsEnumerable","__decorate","decorators","Reflect","decorate","__param","paramIndex","decorator","__metadata","metadataKey","metadataValue","__awaiter","_arguments","generator","fulfilled","__generator","label","sent","trys","ops","verb","op","__values","__read","ar","__spread","__spreadArrays","il","jl","__spreadArray","pack","__await","__asyncGenerator","q","resume","settle","__asyncDelegator","__asyncValues","__makeTemplateObject","cooked","__classPrivateFieldGet","kind","__classPrivateFieldSet","required","controlOrWhitespace","IContents","MIME","FILE","PLAIN_TEXT","OCTET_STREAM","TYPES","getType","defaultType","fileType","fileExt","extensions","mimeTypes","hasFormat","fileFormat","IBroadcastChannelWrapper","IKernels","FALLBACK_KERNEL","IKernelSpecs","KERNEL_ICON_URL","PLUGIN_ID","autoStart","requires","optional","activate","app","serviceWorker","broadcastChannel","pyodideUrl","pipliteWheelUrl","pipliteUrls","pipUrl","disablePyPIFallback","register","PyodideKernel","mountDrive","enabled","DEFAULT_STORAGE_NAME","reduceBytesToString","byte","_serverContents","_storageName","_storageDrivers","_localforage","localforage","storageName","storageDrivers","initStorage","createDefaultStorage","_counters","createDefaultCounters","_checkpoints","createDefaultCheckpoints","storage","counters","checkpoints","defaultStorageOptions","created","file","_incrementCounter","last_modified","mimetype","counter","EMPTY_NB","toPath","_getFolder","serverItem","_getServerContents","contentMap","serverContents","_getServerDirectory","modified","newFile","child","chunk","chunked","originalContent","lastChunk","_handleChunk","slashed","toDelete","forgetPath","copies","normalizeCheckpoint","newContent","escaped","fileUrl","ok","contentText","contentBytes","arrayBuffer","contentBuffer","apiURL","orig_nbformat","nbformat_minor","nbformat","cells","BroadcastChannelWrapper","_onMessage","_channel","_contents","subcontent","defaultDate","dev","nlink","uid","gid","rdev","blksize","blocks","atime","mtime","ctime","_enabled","enable","BroadcastChannel","disable","ObservableMap","_map","_itemCmp","itemCmp","oldVal","keyList","valList","E_CANCELED","__awaiter$2","Semaphore","_maxConcurrency","_cancelError","_queue","_waiters","_value","acquire","locked","isLocked","ticketPromise","_dispatch","runExclusive","release","waitForUnlock","_currentReleaser","releaser","ticket","nextTicket","released","_resolveWaiters","waiter","Mutex","cancelError","_semaphore","KERNEL_WEBSOCKET_PROTOCOL","Kernels","_kernels","_clients","_kernelClients","_kernelspecs","factories","mutex","kernelId","encodedData","handleMessage","processMsg","removeClient","kernelUrl","WS_BASE_URL","runningKernel","sendMessage","wsServer","KernelSpecs","_factories","defaultKernelName","fromEntries","THIRD_PARTY_LICENSES","ILicenses","EMPTY_BUNDLE","packages","Licenses","bundles","_getFederated","appName","_getAppLicenses","appLicensesUrl","labExtensionsUrl","bundle","federated","_getOneFederated","ISessions","Sessions","_sessions","patched","newKernel","_handleKernelShutdown","sessionId","kernelName","nameOrPath","ISettings","Settings","defaultSettingsStorage","pluginId","getAll","setting","allCore","allFederated","_getAll","override","settingsUrl","_overrides","schema","propDefault","entries","ITranslation","Translation","_prevLocale","locale","prev","displayName","nativeName","en","ILocalForage","localforagePlugin","provides","localforageMemoryPlugin","theLocalforage","ensureMemoryStorage","contentsPlugin","started","initialize","contentsRoutesPlugin","router","filename","Response","post","nb","copyFrom","patch","serviceWorkerPlugin","settingsPlugin","settingsRoutesPlugin","pluginPattern","serviceWorkerRegistrationWrapper","what","logStatus","allKernelSpecs","allSpecs","licenses","translation","ClipboardExt","Selector","Platform","ElementExt","getKeyboardLayout","keyboardLayout","copyText","clipboardData","execCommand","boxSizing","style","getComputedStyle","bt","parseFloat","borderTopWidth","bl","borderLeftWidth","br","borderRightWidth","bb","borderBottomWidth","pt","paddingTop","pl","paddingLeft","pr","paddingRight","pb","paddingBottom","borderTop","borderLeft","borderRight","borderBottom","horizontalSum","verticalSum","sizeLimits","minWidth","minHeight","maxWidth","maxHeight","hitTest","clientX","clientY","rect","getBoundingClientRect","left","right","top","bottom","scrollIntoViewIfNeeded","area","er","height","scrollTop","IS_MAC","IS_WIN","IS_IE","IS_EDGE","accelKey","metaKey","ctrlKey","calculateSpecificity","selector","specificityCache","calculateSingle","isValid","validityCache","testElem","querySelector","protoMatchFunc","proto","Element","matchesSelector","mozMatchesSelector","msMatchesSelector","oMatchesSelector","webkitMatchesSelector","elem","ownerDocument","querySelectorAll","re","NEGATION_RE","ID_RE","CLASS_RE","ATTR_RE","PSEUDO_ELEM_RE","PSEDUO_CLASS_RE","TYPE_RE","IGNORE_RE","KeycodeLayout","codes","modifierKeys","_codes","_keys","extractKeys","_modifierKeys","convertToKeySet","isValidKey","isModifierKey","keyForKeydownEvent","keyCode","keySet","EN_US","CommandRegistry","_timerID","_replaying","_keystrokes","_keydownEvents","_keyBindings","_exactKeyMatch","_commands","_commandChanged","_commandExecuted","_keyBindingChanged","commandChanged","commandExecuted","keyBindingChanged","keyBindings","listCommands","hasCommand","addCommand","createCommand","notifyCommandChanged","describedBy","cmd","mnemonic","icon","iconClass","iconLabel","caption","usage","isEnabled","isToggled","isToggleable","isVisible","addKeyBinding","binding","createKeyBinding","processKeydownEvent","isModifierKeyPressed","keystroke","keystrokeForKeydownEvent","_replayKeydownEvents","_clearPendingState","exact","matchKeyBinding","_executeKeyBinding","_startTimer","_clearTimer","_onPendingTimeout","CHORD_TIMEOUT","replayKeyEvent","newArgs","_luminoEvent","msg1","msg2","empty","parseKeystroke","alt","ctrl","normalizeKeystroke","mods","normalizeKeys","winKeys","macKeys","linuxKeys","formatKeystroke","formatSingleKey","formatKey","layout","altKey","shiftKey","asFunc","emptyStringFunc","negativeOneFunc","undefinedFunc","emptyDatasetFunc","trueFunc","falseFunc","validateSelector","bindings","distance","specificity","sqm","matchSequence","targetDistance","td","sp","which","cloneKeyboardEvent","MAC_DISPLAY","WIN_DISPLAY","Backspace","Tab","Enter","Shift","Ctrl","Alt","Escape","PageUp","PageDown","End","Home","ArrowLeft","ArrowUp","ArrowRight","ArrowDown","Delete","Cmd","dfault","bindKeys","userKeys","targ","curr","dist","parentElement","hasAttribute","LinkedList","_first","_last","_size","isEmpty","firstNode","lastNode","node","addLast","removeLast","addFirst","removeFirst","LinkedListNode","insertBefore","ref","_ref","insertAfter","removeNode","_node","Message","isConflatable","conflate","other","ConflatableMessage","MessageLoop","hooks","messageHooks","invokeHandler","passed","retro","messageHook","invokeHook","posted","messageQueue","enqueueMessage","installMessageHook","flush","flushGuard","runMessageLoop","processMessage","sentinel","cleanupHooks","isNull","_onScrollFrame","_scrollTarget","SCROLL_EDGE_SIZE","scrollLeft","_dropAction","_override","_currentTarget","_currentElement","_promise","mimeData","dragImage","proposedAction","supportedActions","PointerEvent","dispatchDragLeave","_finalize","_addListeners","_attachDragImage","handleEvent","_evtPointerMove","_evtPointerUp","_evtKeyDown","moveDragImage","_updateCurrentTarget","_updateDragScroll","button","action","dispatchDrop","_removeListeners","findScrollTarget","prevTarget","currTarget","prevElem","currElem","findElementBehindBackdrop","dispatchDragExit","dispatchDragEnter","dispatchDragOver","_setDropAction","classList","pointerEvents","position","Document","firstElementChild","_detachDragImage","validateAction","overrideCursor","Drag","DragEvent","detail","relatedTarget","related","screenX","screenY","drag","dropAction","doc","lastElementEventSearch","cursorBackdrop","zIndex","elementFromPoint","lastElementSearch","bbox","width","supported","actionTable","supportedTable","offsetX","offsetY","pageXOffset","pageYOffset","dl","dt","dr","shouldScroll","dsw","scrollWidth","clientWidth","dsh","scrollHeight","clientHeight","dragEvent","none","link","alignBackdrop","propagateBackdropScroll","_event","scrollTarget","closest","backdropScrollOrigin","resetBackdropScroll","overrideCursorID","isConnected","capture","passive","backdrop","createCursorBackdrop","VirtualDOM","BoxEngine","Private$j","Private$i","Utils","VirtualText","VirtualElement","tag","attrs","children","renderer","h","bind","abbr","article","aside","audio","bdi","bdo","blockquote","canvas","cite","col","colgroup","datalist","dd","del","dfn","div","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","hr","iframe","img","kbd","legend","li","main","mark","meter","nav","noscript","ol","optgroup","option","output","param","pre","progress","rp","rt","ruby","samp","select","small","strong","sub","summary","sup","tbody","textarea","tfoot","th","thead","time","title","tr","track","ul","var_","video","wbr","realize","createDOMNode","render","oldContent","hostMap","asContentArray","updateContent","before","specialAttrs","setAttribute","htmlFor","addDataset","elemStyle","addStyle","addAttrs","removeContent","newCount","_sentinel","oldNode","lastChild","childNodes","unrender","oldKeyed","firstChild","keyMap","vNode","nextSibling","collectKeys","oldCopy","oldVNode","newVNode","newKey","pair","oldKey","updateAttrs","oldAttrs","newAttrs","removeAttribute","oldDataset","newDataset","updateDataset","oldStyle","newStyle","updateStyle","BoxSizer","sizeHint","minSize","maxSize","stretch","calc","sizers","totalMin","totalMax","totalSize","totalStretch","stretchCount","sizer","hint","nearZero","notDoneCount","freeSpace","distSpace","distStretch","amt","adjust","growLimit","shrinkLimit","grow","shrink","growSizer","shrinkSizer","Title","_label","_caption","_mnemonic","_icon","_iconClass","_iconLabel","_closable","closable","_dataset","Widget","_flags","_layout","_parent","_hiddenMode","HiddenMode","Display","createNode","addClass","setFlag","Flag","IsDisposed","isAttached","detach","testFlag","IsAttached","isHidden","IsHidden","IsVisible","titleProperty","hiddenMode","_toggleHidden","Scale","willChange","ChildMessage","Msg","ParentChanged","DisallowLayout","widget","hasClass","removeClass","toggleClass","toggle","UpdateRequest","fit","FitRequest","ActivateRequest","CloseRequest","show","BeforeShow","clearFlag","AfterShow","hide","BeforeHide","AfterHide","setHidden","notifyLayout","onResize","onUpdateRequest","onFitRequest","onBeforeShow","onAfterShow","onBeforeHide","onAfterHide","onBeforeAttach","onAfterAttach","onBeforeDetach","onAfterDetach","onActivateRequest","onCloseRequest","onChildAdded","onChildRemoved","processParentMessage","ContentVisibility","contentVisibility","BeforeAttach","AfterAttach","BeforeDetach","AfterDetach","ResizeMessage","UnknownSize","attach","Layout","_fitPolicy","fitPolicy","onChildShown","onChildHidden","removeWidget","getHorizontalAlignment","horizontalAlignmentProperty","setHorizontalAlignment","getVerticalAlignment","verticalAlignmentProperty","setVerticalAlignment","LayoutItem","_top","_left","_width","_height","_minWidth","_minHeight","_maxWidth","_maxHeight","contain","limits","clampW","clampH","resized","onAlignmentChanged","PanelLayout","_widgets","widgets","addWidget","insertWidget","attachWidget","moveWidget","removeWidgetAt","detachWidget","clampDimension","Private$h","Private$g","Private$f","Private$e","Private$d","Private$c","Private$b","Private$a","Private$9","Private$8","Utils$1","SplitLayout","widgetOffset","_fixed","_spacing","_dirty","_hasNormedSizes","_sizers","_handles","_box","_alignment","_orientation","orientation","alignment","spacing","handles","absoluteSizes","relativeSizes","setRelativeSizes","sizes","temp","normed","moveHandle","handle","offsetLeft","offsetTop","createHandle","average","averageSize","createSizer","_update","_fit","updateItemPosition","isHorizontal","handleStyle","nVisible","lastHandleIndex","horz","minW","minH","getStretch","box","offsetWidth","offsetHeight","extra","offset","fullOffset","stretchProperty","setStretch","sum","abs","AccordionLayout","_titles","titleSpace","titles","updateTitle","oldTitle","expanded","newTitle","createTitle","replaceChild","titleStyle","createSectionTitle","Panel","createLayout","SplitPanel","_handleMoved","_pressData","_releaseMouse","handleMoved","_evtPointerDown","Renderer","defaultRenderer","AccordionPanel","_widgetSizesCache","_expansionToggled","expansionToggled","_onTitleChanged","collapse","_toggleExpansion","expand","_evtClick","_eventKeyDown","_computeWidgetSize","widgetSizes","newSize","previousSize","widgetToCollapse","sz","currentSize","click","newIndex","focus","titleClassName","_titleID","_titleKeys","_uuid","_nInstance","createCollapseIcon","createTitleKey","aData","BoxLayout","_direction","getSizeBasis","sizeBasisProperty","setSizeBasis","onChildSizingChanged","clampSpacing","BoxPanel","CommandPalette","_activeIndex","_results","commands","_onGenericChange","searchNode","getElementsByClassName","inputNode","contentNode","addItem","createItem","addItems","newItems","removeItemAt","clearItems","_toggleFocused","search","canActivate","renderEmptyMessage","activeIndex","category","renderHeader","active","renderItem","_activatePreviousItem","_activateNextItem","ai","focused","activeElement","formatHeader","createItemClass","createItemDataset","role","renderItemIcon","renderItemContent","renderItemShortcut","formatEmptyMessage","createIconClass","renderItemLabel","renderItemCaption","formatItemLabel","formatItemCaption","formatItemShortcut","kb","keyBinding","fuzzySearch","rgx","rgxMatch","categoryIndices","labelIndices","matchType","scoreCmp","m1","d1","i1","i2","localeCompare","r1","rank","r2","wrapper","spellcheck","CommandItem","scores","matchItems","visited","createResults","trim","Menu","_childIndex","_openTimerID","_closeTimerID","_childMenu","_parentMenu","_aboutToClose","_menuRequested","aboutToClose","menuRequested","parentMenu","childMenu","rootMenu","menu","leafMenu","activeItem","activateNextItem","activatePreviousItem","triggerActiveItem","_cancelOpenTimer","_cancelCloseTimer","_openChildMenu","insertItem","forceX","forceY","openRootMenu","_evtMouseUp","_evtMouseMove","_evtMouseEnter","_evtMouseLeave","_evtMouseDown","collapsedFlags","computeCollapsed","collapsed","onfocus","findMnemonic","multiple","_startCloseTimer","submenu","_startOpenTimer","hitTestMenus","activateFirst","_closeChildMenu","saveWindowData","itemNode","openSubmenu","TIMER_DELAY","aria","createItemARIA","tabindex","renderIcon","renderLabel","renderShortcut","renderSubmenu","formatLabel","formatShortcut","suffix","SUBMENU_OVERLAP","transientWindowDataCache","transientCacheCounter","getWindowData","_getWindowData","tabIndex","MenuItem","k1","windowData","py","cw","ch","opacity","itemRect","upperKey","mn","ContextMenu","_groupByTarget","_idTick","_sortBySelector","groupByTarget","sortBySelector","others","itemCmpRank","s1","s2","availableItems","ARROW_KEYS","TabBar","Private$7","_currentIndex","_titlesEditable","_previousTitle","_dragData","_addButtonEnabled","_tabMoved","_addRequested","_tabCloseRequested","_tabDetachRequested","_tabActivateRequested","_document","tabsMovable","titlesEditable","allowDeselect","addButtonEnabled","insertBehavior","removeBehavior","tabMoved","tabActivateRequested","addRequested","tabCloseRequested","tabDetachRequested","currentTitle","currentIndex","pi","ci","ct","previousIndex","previousTitle","addButtonNode","addTab","insertTab","asTitle","_adjustCurrentForInsert","_adjustCurrentForMove","removeTab","removeTabAt","_adjustCurrentForRemove","clearTabs","releaseMouse","_evtDblClick","CAPTURING_PHASE","_evtKeyDownCapturing","tabHandlingTabindex","_getCurrentTabindex","renderTab","elemTabindex","getAttribute","tabs","tab","innerHTML","onblur","focusedElement","focusable","nextFocused","focusedIndex","addButtonClicked","pressX","pressY","tabPos","tabSize","tabPressPos","targetIndex","tabLayout","contentRect","dragActive","dragAborted","detachRequested","closeIconSelector","dragExceeded","tabRect","tabPressOffset","snapTabLayout","detachExceeded","layoutTabs","finalizeTabPosition","duration","parseTransitionDuration","resetTabPositions","bh","Private$6","Private$5","Private$4","Private$3","Private$2","Private$1","_tabID","_tabKeys","createTabKey","createTabStyle","createTabClass","createTabDataset","createTabARIA","renderCloseIcon","addButtonSelector","DRAG_THRESHOLD","DETACH_THRESHOLD","transitionDuration","margin","marginLeft","marginTop","dx","dy","pressPos","localPos","clientPos","clientSize","targetPos","targetEnd","pxPos","threshold","ideal","tgt","DockLayout","_root","bar","tabBars","iterAllWidgets","iterUserWidgets","selectedWidgets","iterSelectedWidgets","iterTabBars","iterHandles","findSplitNode","holdSizes","saveLayout","holdAllSizes","createConfig","restoreLayout","mainConfig","widgetSet","normalizeAreaConfig","oldWidgets","oldTabBars","oldHandles","tabBar","realizeAreaConfig","createTabBar","_createTabBar","_createHandle","refNode","findTabNode","_insertTab","_insertSplit","_removeWidget","hitTestTabAreas","tabNode","hitTestTabNodes","borderWidth","borderHeight","removeAria","splitNode","syncHandles","maybeParent","childNode","childHandle","TabLayoutNode","splitHandle","gChild","gHandle","gSizer","_createTabNode","addAria","after","findFirstTabNode","merge","_splitRoot","normalizeSizes","GOLDEN_RATIO","sibling","SplitLayoutNode","oldRoot","newRoot","normalizeTabAreaConfig","normalizeSplitAreaConfig","realizeTabAreaConfig","realizeSplitAreaConfig","tabSizer","widgetSizer","tabBarItem","widgetItem","tabBarSizer","createNormalizedSizes","horizontal","fixed","tabId","DockPanel","_drag","_tabsMovable","_tabsConstrained","_layoutModified","_mode","_renderer","_edges","edges","DEFAULT_EDGES","tabsConstrained","overlay","Overlay","layoutModified","createSingleDocumentConfig","LayoutModified","selectWidget","activateWidget","_evtDragEnter","_evtDragLeave","_evtDragOver","_evtDrop","isGeneratedTabBarProperty","_showOverlay","zone","findDropTarget","getDropRef","deltaX","deltaY","xPos","yPos","tabHeight","_onTabMoved","_onCurrentChanged","_onTabCloseRequested","_onTabDetachRequested","_onTabActivateRequested","_onTabAddRequested","cloneNode","_hidden","geo","panel","selected","panelRect","al","at","ab","rx","ry","GridLayout","_rowSpacing","_columnSpacing","_rowStarts","_columnStarts","_rowSizers","_columnSizers","rowCount","reallocSizers","columnCount","rowSpacing","clampValue","columnSpacing","rowStretch","setRowStretch","columnStretch","setColumnStretch","maxRow","maxCol","rowSpanCmp","getCellConfig","row","rowSpan","distributeMin","columnSpanCmp","c1","c2","columnSpan","fixedRowSpace","fixedColSpace","w","cellConfigProperty","setCellConfig","normalizeConfig","portion","MenuBar","_tabFocusIndex","_menus","_overflowMenu","_menuItemSizes","_overflowIndex","_forceItemsPosition","forceItemsPosition","_overflowMenuOptions","overflowMenuOptions","overflowIndex","overflowMenu","activeMenu","menus","openActiveMenu","addMenu","insertMenu","_onMenuAboutToClose","_onMenuMenuRequested","removeMenu","removeMenuAt","clearMenus","_evtFocusOut","_focusItemAt","tabFocusIndex","totalMenuSize","tabbable","overflowMenuTitle","overflowMenuItems","screenSize","_updateOverflowIndex","itemMenus","_positionForMenu","newMenu","oldMenu","decrement","increment","thumb","findPart","scrollBar","thumbNode","trackNode","decrementNode","incrementNode","SingletonLayout","_widget","StackedLayout","orientationFromPlacement","plc","placementToOrientationMap","directionFromPlacement","placementToDirectionMap","Application","_delegate","_plugins","_services","_started","_bubblingKeydown","contextMenu","contextMenuRenderer","shell","getPluginDescription","hasPlugin","isPluginActivated","activated","listPlugins","registerPlugin","createPluginData","ensureNoCycle","registerPlugins","deregisterPlugin","ReferenceError","resolveRequiredService","resolveOptionalService","services","service","deactivate","manifest","findDependents","downstream","activatePlugin","bubblingKeydown","hostID","collectStartupPlugins","attachShell","addEventListeners","deferredPlugins","evtResize","evtKeydown","evtContextMenu","dependencies","visit","trace","dep","newEdges","oldSize","packagesOfInterest","poi","sorted","graph","addEdge","fromNode","toNode","candidate","collection","startPlugins","ignorePlugins","Router","_routes","pattern","_add","MockEventManager","_serverSettings","_router","_serviceManager","route","registerPluginModule","ServiceWorkerManager","_registration","_registrationChanged","workerUrl","registrationChanged","registration","controller","getRegistration","scriptURL","setRegistration","IServiceWorkerManager","WORKER_NAME","Mime","_extensions","define","getExtension","typeMap","hasPath","$1","__webpack_module_cache__","leafPrototypes","getProto","inProgress","dataWebpackPrefix","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","getter","getPrototypeOf","ns","def","getOwnPropertyNames","definition","chunkId","globalThis","script","needAttach","scripts","getElementsByTagName","charset","nc","src","onScriptComplete","doneFns","head","toStringTag","scriptUrl","importScripts","currentScript","baseURI","installedChunks","installedChunkData","errorType","realSrc","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","chunkLoadingGlobal","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file